Go Arrays, Slices and Maps
An array has a fixed length. A slice is a flexible view of an array and is what you normally use. A map stores key-value pairs.
ExampleGo
package main
import (
"fmt"
"sort"
)
func main() {
arr := [3]int{10, 20, 30}
fmt.Println(arr, len(arr))
nums := []int{5, 2, 9}
nums = append(nums, 1)
sort.Ints(nums)
fmt.Println(nums, len(nums), nums[1:3])
ages := map[string]int{"Ada": 36, "Sam": 22}
ages["Lee"] = 41
delete(ages, "Sam")
fmt.Println(ages, len(ages))
v, ok := ages["Nobody"]
fmt.Println(v, ok)
}Output
[10 20 30] 3 [1 2 5 9] 4 [2 5] map[Ada:36 Lee:41] 2 0 false
A lookup in a map can return two values: the value, and an ok flag telling you whether the key was really there.
Quick check
What does append do?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.