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
Dynamic XML parser without Struct in Go
Add N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time
Regular expression to validate email address
Encoding and Decoding using json.Marshal and json.Unmarshal
Simple example of Map initialization in Go
Get Year, Month, Day, Hour, Min and Second from a specified date
Example Function that takes an interface type as value and pointer?
How to read/write from/to file in Golang?
Example to handle GET and POST request in Golang
Higher Order Functions in Golang