package main import ( "fmt" ) // (1) var m = make(map[int]int) // (2)をコメントアウトするならこっちを使う func main() { // (2) //m := map[int]int{} // (1)をコメントアウトするならこっちを使う m[3124] = 9 m[1992] = 2 m[2020] = 3 // キーのみ取り出す for key := range m { fmt.Println(key) } //3124 //1992 //2020 fmt.Println() // キーと値 for key, value := range m { fmt.Println(key, value) } fmt.Println() //1992 2 //2020 3 //3124 9 // 値のみ必要な場合 for _, value := range m { fmt.Println(value) } //9 //2 //3 fmt.Println() // ループの回数を数える i := 0 for key, value := range m { fmt.Println(key, value) i++ } //3124 9 //1992 2 //2020 3 fmt.Println() fmt.Println("delete(m, 1992)") delete(m, 1992) for key, value := range m { fmt.Println(key, value) } //delete(m, 1992) //2020 3 //3124 9 fmt.Println() fmt.Println("add as m[2999] = 2") m[2999] = 2 for key, value := range m { fmt.Println(key, value) } //add as m[2999] = 2 //3124 9 //2999 2 //2020 3 _, ok := m[100] if ok { fmt.Println("OK") } else { fmt.Println("NG") } // NG _, ok = m[2999] if ok { fmt.Println("OK") } else { fmt.Println("NG") } // OK fmt.Println(m) // map[2020:3 2999:2 3124:9] m[2020]++ fmt.Println(m) // map[2020:4 2999:2 3124:9]
}