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?

Goにおけるマップ

Last updated at Posted at 2024-12-29

Maps

キーと値とを関連付ける。

package main

import "fmt"

type Vertex struct {
	Lat, Long float64
}

var m map[string]Vertex

func main() {
	m = make(map[string]Vertex)
	m["Bell Labs"] = Vertex{
		40.68433, -74.39967,
	}
	fmt.Println(m["Bell Labs"])
}
// {40.68433 -74.39967}

マップの初期化

package main

import "fmt"

type Vertex struct {
	Lat, Long float64
}

var m = map[string]Vertex{
	"Bell Labs": Vertex{
		40.68433, -74.39967,
	},
	"Google": Vertex{
		37.42202, -122.08408,
	},
}

func main() {
	fmt.Println(m)
}
// map[Bell Labs:{40.68433 -74.39967} Google:{37.42202 -122.08408}]

挿入、更新

m[key] = elem

要素の取得

elem = m[key]

要素の削除

delete(m, key)

要素が存在確認

2つの目の値で要素の存在確認の結果を取得できる。
mkeyがあれば、変数oktrueとなり、存在しなければ、okfalseとなる。
mapにkeyが存在しない場合、elemmapの要素の型のゼロ値となる。

elem, ok = m[key]
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?