Skip to main content

GoLang - How to check if key exists in map?

package main

import "fmt"

var m map[string]string

func main() {
    m = make(map[string]string)
    m["foo"] = "abc"

    if val, ok := m["foo"]; ok {
        fmt.Println("foo found -", val)
    } else {
        fmt.Println("foo not found")
    }

    if val, ok := m["bar"]; ok {
        fmt.Println("bar found  -", val)
    } else {
        fmt.Println("bar not found")
    }
}


Output:

foo found - abc
bar not found

Comments

Popular posts from this blog

How to delete commits in Git?

Suppose you have 3 commits with SHAs as follows: HEAD~0 --> Commit 3 ccccccc HEAD~1 --> Commit 2 bbbbbbb HEAD~2 --> Commit 1 aaaaaaa If you want to remove the last two commits (i.e., commits 2 and 3) and make Commit 1 as the latest commit, run the following commands: git reset --hard aaaaaaa git push origin HEAD --force Now, the commit history would be as follows: HEAD~0 --> Commit 1 aaaaaaa