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