LoginSignup
76
30

More than 5 years have passed since last update.

Go言語: マップのキーが存在するかチェックしたい

Posted at

Go言語でマップにキーが定義されているのかを調べる方法です。マップのキーを参照すると、値と存在有無のbool値が戻り値になります。このbool値を確認することで、キーの有無が分かります。

package main

import "fmt"

func main() {
    dict := map[string]int{
        "foo": 1,
    }

    if val, ok := dict["foo"]; ok {
        fmt.Printf("foo exists. The value is %#v", val)
    }
}

このコードを実行してみる

76
30
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
76
30