Created
February 17, 2019 02:16
-
-
Save cjgiridhar/abe310972482eed2b4813985b1a5dc94 to your computer and use it in GitHub Desktop.
Working with maps in Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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