A big limitation of static arrays in Go is the fact that once the array is created, it has a fixed size.
The slice overcomes this limitation by having variable size and allowing for elements to be added or removed.
Creation:
You declare a slice by specifying the element type prefixed with [], along with the name of the slice:
var sandwich []string
This code creates an empty slice named sandwich where each item is a string.
Initialization I:
You can also initialize a slice at declaration by using := with a slice literal: the slice type followed by the values inside curly braces {}, with a comma between each entry, like this:
sandwich := []string{"peanut butter", "jelly", "bread"}
We created a slice named sandwich which consists of 3 items: "peanut butter", "jelly" and "bread".
Initialization II:
Another way of initializing a slice at declaration is by listing all elements explicitly in a slice literal, like this:
animals := []string{"cat", "cat", "cat", "cat", "cat"}
We created a slice named animals which consists of 5 "cat" items.
Assignment
Follow the Coding Tutorial and let's create some slices!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
