0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

map

Last updated at Posted at 2019-06-07
func main() {
	m := map[string]int{"apple": 100, "banana": 200}

	fmt.Println(m) //map[apple:100 banana:200]
	fmt.Println(m["apple"]) //100
	m["banana"] = 300
	fmt.Println(m) //map[apple:100 banana:300]

	m["orange"] = 500
	fmt.Println(m) //map[apple:100 banana:300 orange:500]

	fmt.Println(m["nothing"]) //0 intのデフォルト値

	v, ok := m["apple"] //okは中身が入っているかチェックするもの。2つ目の返り値はなくても良い
	fmt.Println(v, ok)  //100 true

	v2, ok2 := m["nothing"]
	fmt.Println(v2, ok2) //0 false

	m2 := make(map[string]int)
	m2["sp"] = 20000
	fmt.Println(m2)
	//メモリ上に空のマップをつくってから値を代入した

	/*
		var m3 map[string]int
		m3["sp"] = 50000
		fmt.Println(m3) //panic: assignment to entry in nil map
		//宣言はしているがメモリ上に入れるマップがないのでエラー
	*/

	var s []int
	if s == nil {
		fmt.Println("NIL")
	}
	//varで宣言した場合は、mapもスライスもnil
}

【参考】
現役シリコンバレーエンジニアが教えるGo入門(https://www.udemy.com/share/100BhMB0obeFpbTX4=/)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?