Skip to content

Commit f4eaa79

Browse files
authored
Merge pull request #97 from devlights/issue-#40-map-access
Add map access example ( close #40 )
2 parents 5f8af0e + 34c72ed commit f4eaa79

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

basic/map_/map_access.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package map_
2+
3+
import "fmt"
4+
5+
func MapAccess() error {
6+
7+
var (
8+
f = func(key string, val int, ok bool) {
9+
fmt.Printf("m[%v]\tval: %v\tok: %v\n", key, val, ok)
10+
}
11+
12+
m = map[string]int{
13+
"a": 100,
14+
"b": 200,
15+
}
16+
)
17+
18+
// -------------------------------------------------------------
19+
// Go の場合、mapに対応するキーが存在するかどうかの確認は
20+
// 実際に map に対してアクセスした際に戻り値で返ってくる bool の値で判別できる
21+
// -------------------------------------------------------------
22+
// 存在する場合
23+
val, ok := m["a"]
24+
f("a", val, ok)
25+
26+
// 存在しない場合
27+
val, ok = m["not_exists"]
28+
f("not_exists", val, ok)
29+
30+
// このパターンには定型が存在する. この書き方はGoでよく見る書き方である.
31+
if val, ok = m["a"]; ok {
32+
f("存在するパターン", val, ok)
33+
}
34+
35+
if val, ok = m["not_exists"]; !ok {
36+
f("存在しないパターン", val, ok)
37+
}
38+
39+
return nil
40+
}

lib/mapping.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ func (m SampleMapping) MakeMapping() {
4545
m["map_for"] = map_.MapFor
4646
m["map_initialize"] = map_.MapInitialize
4747
m["map_delete"] = map_.MapDelete
48+
m["map_access"] = map_.MapAccess
4849
m["scope01"] = scope.Scope01
4950
m["async01"] = async.Async01
5051
m["reflection01"] = reflection.Reflection01

0 commit comments

Comments
 (0)