capypad
0 day streak
go / beginner
Snippet

Understanding Go Maps

Maps in Go are unordered key-value data structures. They are created using the built-in `map` keyword with syntax `map[KeyType]ValueType`. You can add entries using bracket notation, check for existence using the comma-ok idiom, delete entries with the `delete()` function, and iterate over all entries with `range`. Maps return the zero value for missing keys.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main
 
import "fmt"
 
func main() {
scores := map[string]int{
"Alice": 95,
"Bob": 87,
"Charlie": 92,
}
 
scores["Diana"] = 88
 
if score, exists := scores["Bob"]; exists {
fmt.Printf("Bob's score: %d\n", score)
}
 
delete(scores, "Charlie")
 
for name, score := range scores {
fmt.Printf("%s: %d\n", name, score)
}
}
Breakdown
1
scores := map[string]int{
Declares a map with string keys and int values
2
"Alice": 95,
Initializes with three key-value pairs
3
scores["Diana"] = 88
Adds a new entry to the map
4
if score, exists := scores["Bob"]; exists {
Comma-ok idiom checks if key exists and retrieves value
5
delete(scores, "Charlie")
Removes an entry from the map
6
for name, score := range scores {
Iterates over all key-value pairs