go · level 1 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A keeps many values together, in order.
A slice is a list of values kept in one box, in order, like a shopping list. snacks := []string{"crisps", "apple", "cake"} makes a slice of three strings.
[]string says the slice holds strings. A slice of whole numbers is []int. Each value in a slice is an , and every item must be the same type.
len(snacks) counts the items. fmt.Println(snacks) shows the whole slice inside square brackets, with spaces between the items.
package main
import "fmt"
func main() {
snacks := []string{"crisps", "apple", "cake"}
scores := []int{7, 9, 4}
fmt.Println(snacks)
fmt.Println(len(snacks), "snacks")
fmt.Println(scores)
} The items go inside curly brackets, with a comma between each one.
guess first
Count the pets. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
pets := []string{"cat", "dog", "goldfish"}
fmt.Println(len(pets))
fmt.Println(pets)
}
your turn
Your turn. List your favourite films.
Type three favourite films between the quotes. Keep the commas between them, then press run.
output
press run to see what happens
fix it
One score is the wrong type. Fix it!
output
press run to see what happens
- Read the error. Go cannot put a string into a slice of
int. - Every item in
[]intmust be a whole number, but one of them is written in words. - Change "nine" to 9 with no quotes, then press run.
nailed it
you packed lots of values into one box. :D
- A slice keeps many items together, in order.
[]stringholds strings and[]intholds whole numbers.lencounts the items in a slice.
new words in your collection
- slice
- item
This lesson isn’t saved. A free account remembers every lesson you finish.