Created
January 25, 2015 10:32
-
-
Save giwa/189caa24290e37a38929 to your computer and use it in GitHub Desktop.
Go by Example: Maps ref: http://qiita.com/giwa@github/items/96d0929bf1c906a398cb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
// 空のmapを作るためにbuildinのmakeを使います。 | |
// make(map[key-type]val-type) | |
m := make(map[string]int) | |
// kye/valueのペアをセットするには典型的な文法の name[key] = val を使います。 | |
m["k1"] = 7 | |
m["k2"] = 13 | |
// mapを表示させる。 | |
// 例として Printlnはすべてのkey/valueペアを表示する。 | |
fmt.Println("map:", m) | |
// name[key]でkeyに対するvalueを取得する | |
v1 := m["k1"] | |
fmt.Println("v1: ", v1) | |
// build inのlenはmapで呼ばれた際key/valueペアの数を返す。 | |
fmt.Println("len:", len(m)) | |
// build in deleteはkey/value ペアをmapから消去します。 | |
delete(m, "k2") | |
fmt.Println("map:", m) | |
// 値をmapから取得する際、オプションとして、二個目の値を返す。 | |
// これはkeyがmapに存在したかどうかを示すものである。 | |
// これはkeyが存在しない場合と、keyの値が0や、""などのzero valueかどうかの曖昧さをなくすために使えるだろう。 | |
// ここでは、value自体はいらないので、 blankをしめす _で無視する。 | |
_, prs := m["k2"] | |
fmt.Println("prs:", prs) | |
// 新しいmapの宣言と初期化はこのような文法で同じラインで出来る。 | |
n := map[string]int{"foo": 1, "bar": 2} | |
fmt.Println("map:", n) | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go run maps.go | |
map: map[k1:7 k2:13] | |
v1: 7 | |
len: 2 | |
map: map[k1:7] | |
prs: false | |
map: map[foo:1 bar:2] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment