# Arrays and Slices in Go
In this section, arrays and slices are introduced.
In Go, the size of an array is a part of the type. Therefore, arrays have a fixed size. The declaration has the following syntax:
You can access the data with
array[index]. You can see this with a cross product:
The compiler fits the array depending on the number of elements.
The previous example code is not well-written, but it demonstrates different aspects of arrays.
len(array) is a built-in function that gives the size of an array.
defer is used to defer the execution of last-in-first-out order until surrounding functions return.
In Go, a slice is an abstraction built on top of arrays. Slices are more flexible than arrays and are used more often than arrays because of this flexibility.
A slice does not have a fixed size. To declare a slice, use the following:
A slice has a length (
len(slice)) and a capacity (
You can also use a built-in function to declare a slice:
func make(type, length, capacity) type. This returns a slice with the given length, capacity, and type. It allocates an array, which is referred to by the returned slice.
Now create a simple slice with three vectors, and then add a vector with the built-in
func append(s T, vs ...T)  T function:
You can use
range to iterate over an array, a slice, or a map.
i is the index, and
v is the value of that index.
There is also a built-in
func copy(dst, src T) int to copy one slice into another and return the number of copied elements.
Maps are stored key/value pairs. The declaration is as follows:
However, this creates a
nil map, which is not so useful. You can read such a map but not write to it. You use
make to initialize a map so you can write to it. The following is more useful:
Now you can work with maps:
The built-in function
func delete(m map[Type]Type1, key Type) deletes the element with the key from the map.
When iterating over maps, the order is not deterministic.
To summarize, this section has explored:
- How the size of an array is part of the type, therefor arrays have a fixed size.
- How slices are flexible abstractions built on top of arrays.
- How maps are stored key/value pairs.