Skip to content

Instantly share code, notes, and snippets.

@cjgiridhar
Created February 17, 2019 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjgiridhar/abe310972482eed2b4813985b1a5dc94 to your computer and use it in GitHub Desktop.
Save cjgiridhar/abe310972482eed2b4813985b1a5dc94 to your computer and use it in GitHub Desktop.
Working with maps in Golang
package main
import "fmt"
func main() {
var mscores = make(map[string]int)
mscores["Chetan"] = 90
mscores["John"] = 75
mscores["Alice"] = 30
// Returns Alice score: 30
fmt.Println("Alice score:", mscores["Alice"])
// Iterating over contents of a map, code returns
// Key: Alice Value: 30
// Key: Chetan Value: 90
// Key: John Value: 75
for key, value := range mscores {
fmt.Println("Key:", key, "Value:", value)
}
// Returns Bob's score: 0 (uses the zero value)
fmt.Println("Bob's score:", mscores["Bob"])
// Returns Length of mscores map: 3
fmt.Println("Length of mscores map:", len(mscores))
// Checks if the key exists in a map
// i returns the value for the key if exists or returns the zero value
// ok returns bool value indicating if the key exists
i, ok := mscores["Bob"]
// Returns i, ok 0 false
// As the key Bob doesnt exist, i returns zero value 0
// and ok returns false which indicates non existence of key
fmt.Println("i, ok", i, ok)
// Delete element from the map
delete(mscores, "Alice")
// Returns mscores map[John:75 Chetan:90]
// Alice key is removed from the map
fmt.Println("mscores", mscores)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment