go / beginner
Snippet
Maps: Go's Key-Value Collections
Maps are Go's built-in hash table implementation for storing key-value pairs. They grow dynamically and accessing a non-existent key returns the zero value of the value type. The comma-ok idiom lets you distinguish between a missing key and an actual zero value.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package mainimport "fmt"func main() {scores := map[string]int{"Alice": 95,"Bob": 87,}scores["Charlie"] = 92fmt.Println("Bob's score:", scores["Bob"])value, exists := scores["David"]fmt.Printf("David: %d, exists: %t\n", value, exists)delete(scores, "Bob")fmt.Println("Scores:", scores)}
Breakdown
1
scores := map[string]int{
Declares map with string keys and int values
2
"Alice": 95,
Key-value pair added during initialization
3
scores["Charlie"] = 92
Adds new key-value pair to existing map
4
value, exists := scores["David"]
Two-value access: first is value, second is boolean existence flag
5
delete(scores, "Bob")
Built-in function removes key and its value from map