go / beginner
Snippet
Maps: Go's Key-Value Data Structure
Maps in Go are unordered collections of key-value pairs. They are created with the map keyword followed by the key type in brackets and the value type. You can access values using the key in square brackets, and check if a key exists using the comma-ok idiom. The delete function removes entries, and range iterates over all key-value pairs.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package mainimport "fmt"func main() {ages := map[string]int{"Alice": 30,"Bob": 25,"Carol": 35,}fmt.Println("Bob's age:", ages["Bob"])ages["David"] = 28age, exists := ages["Eve"]if exists {fmt.Println("Eve exists with age:", age)} else {fmt.Println("Eve not found")}delete(ages, "Carol")for name, age := range ages {fmt.Printf("%s is %d years old\n", name, age)}}
Breakdown
1
ages := map[string]int{...}
Creates a map with string keys and int values
2
ages["Bob"]
Accesses the value for key "Bob", returns 25
3
age, exists := ages["Eve"]
Comma-ok idiom: exists is false if key not found
4
delete(ages, "Carol")
Removes the key-value pair for "Carol"
5
for name, age := range ages
Iterates over all key-value pairs in random order