LoginSignup
10
5

More than 5 years have passed since last update.

Slice、Mapの存在チェック

Posted at

Sliceの存在チェック

  • Array/Sliceのlengthをチェックしなければならない
package main

import (
    "fmt"
)

func main() {
    row := []string{"1", "2", "3"}

    if len(row) >= 3 {
        fmt.Println(row[2])
    }

    if len(row) >= 4 {
        fmt.Println(row[3])
    }
}

Mapの存在チェック

  • MapのKeyを参照すると、2つめの返り値でそのKeyが存在しているかどうかのbool値を返すので、それをチェック
package main

import (
    "fmt"
)

func main() {
    m := map[string]int{"a": 1, "b": 2, "c": 3}

    if v, ok := m["a"]; ok {
        fmt.Println(v)
    }

    if v, ok := m["d"]; ok {
        fmt.Println(v)
    }   
}

10
5
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
10
5