- An array type definition specifies a length and an element type.
- For example, the type [4]int represents an array of four integers.
- An array's size is fixed
- Arrays can be indexed in the usual way, so the expression s[n] accesses the nth element, starting from zero.
- Arrays do not need to be initialized explicitly; the zero value of an array is a ready-to-use
- An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C).
- When you assign or pass around an array value you will make a copy of its contents.
An array literal can be specified like so:
b := [2]string{"Penn", "Teller"}
Or, you can have the compiler count the array elements for you:
b := [...]string{"Penn", "Teller"}
In both cases, the type of b is [2]string.
- They build on arrays to provide great power and convenience.
- The type specification for a slice is []T.
- A slice type has no specified length.
- Declaration:
letters := []string{"a", "b", "c", "d"}
- A slice can be created with the built-in function called make
- make function takes a type, a length, and an optional capacity
var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}
- When the capacity argument is omitted, it defaults to the specified length.
- The zero value of a slice is nil. The len and cap functions will both return 0 for a nil slice.
- A slice can also be formed by "slicing" an existing slice or array.
- Slicing is done by specifying a half-open range with two indices separated by a colon.
- The expression b[1:4] creates a slice including elements 1 through 3 of b (the indices of the resulting slice will be 0 through 2).