Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions basic/map_/map_access.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package map_

import "fmt"

func MapAccess() error {

var (
f = func(key string, val int, ok bool) {
fmt.Printf("m[%v]\tval: %v\tok: %v\n", key, val, ok)
}

m = map[string]int{
"a": 100,
"b": 200,
}
)

// -------------------------------------------------------------
// Go の場合、mapに対応するキーが存在するかどうかの確認は
// 実際に map に対してアクセスした際に戻り値で返ってくる bool の値で判別できる
// -------------------------------------------------------------
// 存在する場合
val, ok := m["a"]
f("a", val, ok)

// 存在しない場合
val, ok = m["not_exists"]
f("not_exists", val, ok)

// このパターンには定型が存在する. この書き方はGoでよく見る書き方である.
if val, ok = m["a"]; ok {
f("存在するパターン", val, ok)
}

if val, ok = m["not_exists"]; !ok {
f("存在しないパターン", val, ok)
}

return nil
}
1 change: 1 addition & 0 deletions lib/mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func (m SampleMapping) MakeMapping() {
m["map_for"] = map_.MapFor
m["map_initialize"] = map_.MapInitialize
m["map_delete"] = map_.MapDelete
m["map_access"] = map_.MapAccess
m["scope01"] = scope.Scope01
m["async01"] = async.Async01
m["reflection01"] = reflection.Reflection01
Expand Down