Go, lesson 7
One variable holds one value. To work with a shopping list, a set of scores or a phone book, you need a collection. Go has three built in: arrays, slices and maps.
An array has a length that is part of its type. [3]int and [4]int are different types.
Indexes start at 0. Reading days[7] crashes the program with an "index out of range"
panic. Because their size is fixed, arrays are used less often than slices.
A slice is a flexible view of a list. Its type, []int, has no length. You create one with
a literal, or start empty and grow it with the built-in append:
append returns the updated slice, so always assign the result back. To create a slice of a
known length filled with zero values, use make:
2 exercises to try what you just read.
You can take part of a slice with s[low:high], which includes low but not high:
A sub-slice shares the same underlying storage as the original. Changing first[0] also
changes scores[0]. Lesson 14 explores this in depth.
for ... range walks over a slice, giving you the index and a copy of each element:
Use _ for the part you do not need: for _, s := range scores gives just the values.
A map links keys to values, like a dictionary links words to definitions. The type
map[string]int maps strings to ints.
Reading a missing key returns the zero value, so stock["kiwi"] is 0. That makes counting
easy: counts[word]++ works even for a brand-new word. To tell "missing" apart from "zero",
use the two-value form:
An empty map is made with make(map[string]int) or map[string]int{}. Do not write to a map
declared with just var m map[string]int; it is nil and writing panics.
Ranging over a map gives key and value, but the order is random and changes from run to run. When output order matters, keep the keys in a slice and loop over that, or sort them (lesson 12).
The slices package has ready-made functions such as slices.Contains(s, v),
slices.Index(s, v) and slices.Max(s). Go also has built-in min and max functions that
take any number of arguments: max(3, 9, 4) is 9.
The first number is a count n, followed by n test scores. Print the average with one
decimal, then on the next line print every score that is strictly above the average, in the
original order, separated by spaces. If no score is above the average, print none.
Sample input:
Sample output:
Each line of input holds one vote: a candidate's name. Count the votes and print each
candidate with their total, in the order each name first appeared, as name: count.
Sample input:
Sample output:
var podium [3]string
podium[0] = "Ana"
days := [7]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
fmt.Println(len(days), days[6]) // 7 Sunscores := []int{70, 85, 92}
scores = append(scores, 60) // [70 85 92 60]
fmt.Println(len(scores), scores[1]) // 4 85counts := make([]int, 5) // [0 0 0 0 0]first := scores[:2] // [70 85]
rest := scores[2:] // [92 60]for i, s := range scores {
fmt.Println(i, s)
}stock := map[string]int{"apple": 5, "pear": 2}
stock["plum"] = 9 // add or replace
stock["apple"]-- // update in place
delete(stock, "pear") // remove
fmt.Println(len(stock)) // 2qty, ok := stock["kiwi"]
if !ok {
fmt.Println("no kiwis")
}5
70 85 92 60 7877.0
85 92 78kiwi
mango
kiwi
fig
kiwi
mangokiwi: 3
mango: 2
fig: 1