1
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 3 years have passed since last update.

【Go】マップサンプルメモ

Posted at

サンプル

package main

import (
	"fmt"
)

func main() {
	mapTest := make(map[string]int)

	mapTest["a"] = 1
	mapTest["b"] = 2

	fmt.Println(mapTest["a"]) // 1
	fmt.Println(mapTest) // map[a:1 b:2]
	fmt.Println(mapTest["c"]) // 0 -- > 存在しないキーのときは値の型のゼロ値が返る

	for k, v := range mapTest {
		fmt.Println(k, v) // a 1
	}

	// 存在チェック
	// マップ内に指定のキーに対する値が存在しているかは、戻り値を2つ受けて、2番目の戻り値で判断することができる
	// https://blog.y-yuki.net/entry/2017/04/26/000000
	_, ok := mapTest["a"]
	fmt.Println(ok) // true

	_, ok = mapTest["c"]
	fmt.Println(ok) // false

	// 削除
	delete(mapTest, "a")
	fmt.Println(mapTest) // [b:2

	// 代入
	mapTest["d"] = 4
	fmt.Println(mapTest) // map[b:2 d:4]

	// 初期化
	mapTest2 := map[string]int{
		"A": 1,
		"B": 2}
	fmt.Println(mapTest2) // map[A:1 B:2]
}

参考

入門Goプログラミング
入門Goプログラミング
posted with amazlet at 20.02.15
Nathan Youngman Roger Peppé
翔泳社
売り上げランキング: 116,400
1
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
1
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?