Coding for All
Lesson 14: Indexes and len
Indexes and len Pick single items out of a slice.
1package main
2
3import "fmt"
4
5func main() {
6 fruits := []string{"apple", "banana", "cherry"}
7 fmt.Println(fruits[0])
8 fmt.Println(len(fruits))
9}
Terminal
$ go run main.go
apple
3
Every line, explained
package main
Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import "fmt"
import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
func main() {
func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
fruits := []string{"apple", "banana", "cherry"}
A slice is Go's list. []string means "a slice of strings", and the items go between curly braces. Every item must be the same type.
fmt.Println(fruits[0])
You get one item using its index (position) in square brackets, and counting starts at 0, not 1! fruits[0] is "apple", fruits[1] is "banana", fruits[2] is "cherry".
fmt.Println(len(fruits))
len(...) tells you how many items a slice holds: here, 3. It works on strings too: len("hi") is 2.
}
This closing brace } ends func main.