Example: Arrays of Arrays, Arrays of Slices, Slices of Arrays and Slices of Slices
Using dots ... instead of length when declaring an array instructs the compiler to calculate the length by including three dots in place of length declaration
[:]
assigns all element value of array to slicearrayofarrays
is a multidimensional arrayExample
package main
import "fmt"
func main() {
println("Simple Array:")
var arrayint = [...]int{1, 2, 3, 4} //assign
fmt.Println(arrayint, "\n")
println("Simple Slice:")
var sliceint []int
sliceint = arrayint[:] //assign
fmt.Println(sliceint, "\n")
println("Array of arrays:")
var arrayofarrays [3][len(arrayint)]int
for i := range arrayofarrays { //assign
arrayofarrays[i] = arrayint
}
fmt.Println(arrayofarrays, "\n")
println("Array of slices:")
var arrayofslice [len(arrayofarrays)][]int
for i := range arrayofarrays { // assign
arrayofslice[i] = arrayofarrays[i][:]
}
fmt.Println(arrayofslice, "\n")
println("Slice of arrays:")
var sliceofarray [][len(arrayint)]int
sliceofarray = arrayofarrays[:]
fmt.Println(sliceofarray, "\n")
println("Slice of slices:")
var sliceofslices [][]int
sliceofslices = arrayofslice[:]
fmt.Println(sliceofslices, "\n")
}
Output
Simple Array:
[1 2 3 4]
Simple Slice:
[1 2 3 4]
Array of arrays:
[[1 2 3 4] [1 2 3 4] [1 2 3 4]]
Array of slices:
[[1 2 3 4] [1 2 3 4] [1 2 3 4]]
Slice of arrays:
[[1 2 3 4] [1 2 3 4] [1 2 3 4]]
Slice of slices:
[[1 2 3 4] [1 2 3 4] [1 2 3 4]]
Most Helpful This Week
How to Decode or Unmarshal bi-dimensional array of integers?
How to check string contains uppercase lowercase character in Golang?
Subtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.
How to use for and foreach loop?
How to create Empty and Nil Slice?
Golang Convert String into Snake Case
Regular expression to extract domain from URL
How to create a photo gallery in Go?
How to check if a string contains certain characters in Golang?
Convert Float32 to Float64 and Float64 to Float32