Create array
suggest changeAn array is a fixed size collection of elements of the same type.
To declare an int array of 5 elements: var arr = [5]int
Below is a code example showing different ways to create an array.
// Creating arrays of 6 elements of type int
var array1 = [6]int{1, 2, 3, 4, 5, 6}
// the compiler will derive the size of the array
var array2 = [...]int{1, 2, 3, 4, 5, 6}
fmt.Println("array1:", array1)
fmt.Println("array2:", array2)
// Creating arrays with default values inside:
zeros := [8]int{} // an array of 8 ints, each 0
ptrs := [8]*int{} // an array of 8 int pointers, each nil
emptystr := [8]string{} // an array of 8 strings, each ""
fmt.Println("zeroes:", zeros) // > [0 0 0 0 0 0 0 0]
fmt.Println("ptrs:", ptrs) // > [<nil> <nil> <nil> <nil> <nil> <nil> <nil> <nil>]
fmt.Println("emptystr:", emptystr) // > [ ]
// values are empty strings, separated by spaces,
// so we can just see separating spaces
// Arrays work with a named type as well.
type Data struct {
Number int
Text string
}
// Creating an array with 8 'Data' elements
// All the 8 elements will be like {0, ""} (Number = 0, Text = "")
structs := [8]Data{}
fmt.Println("structs:", structs) // > [{0 } {0 } {0 } {0 } {0 } {0 } {0 } {0 }]
// prints {0 } because Number is 0 and Text is empty; a space separates them
array1: [1 2 3 4 5 6]
array2: [1 2 3 4 5 6]
zeroes: [0 0 0 0 0 0 0 0]
ptrs: [<nil> <nil> <nil> <nil> <nil> <nil> <nil> <nil>]
emptystr: [ ]
structs: [{0 } {0 } {0 } {0 } {0 } {0 } {0 } {0 }]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents