Go の基礎
Go Maps
Store values under keys: add, read, check, delete and loop in a fixed order.
学べること
- Creating and updating
- The value, ok form
- Sorting the keys
stock
"apple"5"pear"5"plum"1Values found by key
A map stores values under keys, so you can find a value quickly by its key. It is Go's version of a dictionary or hash table.
Reading a missing key returns the zero value, so the second result, found, tells you whether the key exists. delete removes a key. A map has no fixed order, so the keys are collected and sorted before printing.
重要なポイント
- A missing key reads as the zero value.
- value, found :=
m[key]tells you if it exists. - Map order is random: sort the keys.
実行できる Go のサンプル
Go
main.go
package main
import (
"fmt"
"sort"
)
func main() {
stock := map[string]int{"apple": 3, "pear": 5}
stock["plum"] = 1
stock["apple"] += 2
fmt.Println(stock["apple"], len(stock))
count, found := stock["kiwi"]
fmt.Println(count, found)
delete(stock, "pear")
names := make([]string, 0, len(stock))
for name := range stock {
names = append(names, name)
}
sort.Strings(names) // map order is random, so sort the keys
for _, name := range names {
fmt.Println(name, stock[name])
}
}
5 3
0 false
apple 5
plum 1練習
サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。
このレッスンを終えましたか?
学習済みにすると進み具合を記録できます。
進み具合はこのブラウザーに保存されています ログインすると、どのデバイスでも引き継げます。
チャレンジで練習する
このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。
すべてのチャレンジ