Newer
Older
01_hello / collection / map.go
yhornisse on 24 Sep 2021 945 bytes add map sample
package main

import "fmt"

func main() {
	cal := map[string]int{
		"Jan": 1,
		"Feb": 2,
		"Mar": 3,
		"Apr": 4,
		"May": 5,
		"Jun": 6,
		"Jul": 7,
		"Aug": 8,
		"Sep": 9,
		"Oct": 10,
		"Nov": 11,
		"Dec": 12,
	}
	fmt.Printf("%+v\n", cal) // map[Apr:4 Aug:8 Dec:12 Feb:2 Jan:1 Jul:7 Jun:6 Mar:3 May:5 Nov:11 Oct:10 Sep:9]
	fmt.Printf("%d\n", cal["Jan"]) // 1
	fmt.Printf("%d\n", cal["hoge"]) // 0 存在しない場合はゼロ値
	fmt.Printf("%d\n", len(cal)) // 12
	fmt.Println()

	for name, num := range cal {// 準不定
		fmt.Printf("%d: %s\n", num, name)
	}
	fmt.Println()

	v1 := map[string]int{}
	v1["hoge"] = 100
	v1["fuga"] = 0
	{
		v, ok := v1["hoge"]
		fmt.Printf("v: %d ok: %v\n", v, ok) // v: 100 ok: true
	}
	{
		v, ok := v1["fuga"]
		fmt.Printf("v: %d ok: %v\n", v, ok) // v: 0 ok: true
	}
	{
		v, ok := v1["piyo"]
		fmt.Printf("v: %d ok: %v\n", v, ok) // v: 0 ok: false
	}

	var v2 map[string]int
	v2["fuga"] = 1 // panic
}