Showing posts with label go map. Show all posts
Showing posts with label go map. Show all posts

Friday, 10 May 2019

Go: Map: Check for the existence of key in Go


Below snippet is used to check for the existence of key in a map.

if value, ok := map[key]; ok {
    //If key exists in the map, then this code will get executed
} else {
    //If key not exists in the map, then this code will get executed
}

If ‘key’ exists in the map, then the variable ‘ok’ is set to true, and value associated with key is assigned to ‘value’.

If ‘key’ is not exists in the map, then the variable ‘ok’ is set to false, and value is set to ‘zero’ value.

App.go
package main

import "fmt"

func main() {
    employees := make(map[int]string)

    employees[1] = "Krishna"
    employees[2] = "Chamu"
    employees[123] = "Ram"

    key1 := 123

    if value, ok := employees[key1]; ok {
        fmt.Printf("Employee name for the id %v is %v \n", key1, value)
    } else {
        fmt.Printf("Employee with id %v is not exist\n", key1)
    }

    key2 := 125

    if value, ok := employees[key2]; ok {
        fmt.Printf("Employee name for the id %v is %v \n", key2, value)
    } else {
        fmt.Printf("Employee with id %v is not exist\n", key2)
    }
}

Output
Employee name for the id 123 is Ram
Employee with id 125 is not exist


Previous                                                 Next                                                 Home

Friday, 3 May 2019

Go language: Print key, value from map


You can print key, values from a map using for loop.

Example
for key, value := range employees {
         fmt.Println(key, " : ", value)
}

App.java
package main

import "fmt"

func main() {

 employees := map[int]string{
  1: "Krishna",
  2: "Ram",
  3: "Chamu", //Must have trailing comma
 }

 for key, value := range employees {
  fmt.Println(key, " : ", value)
 }
}

Output
1  :  Krishna
2  :  Ram
3  :  Chamu


Previous                                                 Next                                                 Home

Go language: Print all the keys of map


You can print all the keys of a map using for loop.

Example
for key := range employees {
         fmt.Println(key)
}

App.go
package main

import "fmt"

func main() {

 employees := map[int]string{
  1: "Krishna",
  2: "Ram",
  3: "Chamu", //Must have trailing comma
 }

 for key := range employees {
  fmt.Println(key)
 }
}

Output
1
2
3

Previous                                                 Next                                                 Home