

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Arrays in Go
incomplete
2: Slices in Go
incomplete
3: Slices Review
incomplete
4: Make
incomplete
5: Len and Cap Review
incomplete
6: Variadic
incomplete
7: Append
incomplete
8: Range
incomplete
9: Slice of Slices
incomplete
10: Tricky Slices
incomplete
11: Message Filter
incomplete
12: Password Strength
incomplete
13: Message Tagger
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Most of the time we don't need to think about the underlying array of a slice. We can create a new slice using the make function:
// func make([]T, len, cap) []T
mySlice := make([]int, 5, 10)
// the capacity argument is usually omitted and defaults to the length
mySlice := make([]int, 5)
Slices created with make will be filled with the zero value of the type.
If we want to create a slice with a specific set of values, we can use a slice literal:
mySlice := []string{"I", "love", "go"}
Notice the square brackets do not have a 3 in them. If they did, you'd have an array instead of a slice.
The length of a slice is simply the number of elements it contains. It is accessed using the built-in len() function:
mySlice := []string{"I", "love", "go"}
fmt.Println(len(mySlice)) // 3
The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice. It is accessed using the built-in cap() function:
mySlice := []string{"I", "love", "go"}
fmt.Println(cap(mySlice)) // 3
Generally speaking, unless you're hyper-optimizing the memory usage of your program, you don't need to worry about the capacity of a slice because it will automatically grow as needed.
A programming concept you should already be familiar with is array indexing. You can access or assign a single element of an array or slice by using its index.
mySlice := []string{"I", "love", "go"}
fmt.Println(mySlice[2]) // go
mySlice[0] = "you"
fmt.Println(mySlice) // [you love go]
We send a lot of text messages at Textio, and our API is getting slow and unresponsive.
If we know the rough size of a slice before we fill it up, we can make our program faster by creating the slice with that size ahead of time so that the Go runtime doesn't need to continuously allocate new underlying arrays of larger and larger sizes. By setting the length, the slice can still be resized later, but it means we can avoid all the expensive resizing since we know what we'll need.
Complete the getMessageCosts() function. It takes a slice of messages and returns a slice of message costs.