Go Map check key existence

Introduction

Accessing an element of a map can return two values instead of just one.

The first value is the result of the lookup, the second tells us whether or not the lookup was successful.

In Go, we often see code like this:

if name, ok  := elements["Un"]; ok { 
    fmt.Println(name, ok) 
} 
package main//from w w w.  j a va  2 s .co m

import "fmt" 

func main() { 
    elements  := make(map[string]string) 
    elements["H"] = "Hydrogen" 
    elements["Ne"] = "Neon" 

    fmt.Println(elements[""]) 
    
    if name, ok  := elements["Un"]; ok { 
        fmt.Println(name, ok) 
    }else{
        fmt.Println("not found") 
    }
} 



PreviousNext

Related