1. Introduction
Maps are a fundamental data structure in Go, allowing you to store pairs of keys and values. They're similar to what other languages call "hash tables" or "dictionaries". This blog post will cover creating, using, and manipulating maps in Go.
Definition
A map in Go is a built-in data type that associates values of one type (the key) with values of another type (the value). The key can be of any type for which the equality operator is defined, such as integers, strings, and more.
2. Program Steps
1. Declare a map and add key-value pairs.
2. Retrieve values and check for their existence in the map.
3. Iterate over key-value pairs in the map.
4. Delete key-value pairs from the map.
5. Initialize a map using map literals.
3. Code Program
package main
import "fmt"
func main() {
// Step 1: Declare a map
m := make(map[string]int)
// Step 1: Add key-value pairs
m["k1"] = 7
m["k2"] = 13
// Step 2: Retrieve values
val1 := m["k1"]
fmt.Println("val1:", val1)
// Step 2: Check for existence
_, prs := m["k2"]
fmt.Println("prs:", prs)
// Step 3: Iterate over map
fmt.Println("map:")
for k, v := range m {
fmt.Printf("%s -> %d\n", k, v)
}
// Step 4: Delete a key
delete(m, "k2")
fmt.Println("map:", m)
// Step 5: Map literal initialization
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)
}
Output:
val1: 7 prs: true map: k1 -> 7 k2 -> 13 map: map[k1:7] map: map[bar:2 foo:1]
Explanation:
1. package main - The package declaration for the Go program.
2. import "fmt" - Imports the Format package for formatted output.
3. make(map[string]int) is used to create a new map m.
4. m["k1"] = 7 and m["k2"] = 13 add key-value pairs to the map.
5. val1 := m["k1"] retrieves the value for the key "k1" from the map.
6. _, prs := m["k2"] checks if the key "k2" is present in the map. The boolean prs will be true if "k2" is in the map.
7. for k, v := range m iterates over the map, printing each key-value pair.
8. delete(m, "k2") removes the key "k2" from the map.
9. n := map[string]int{"foo": 1, "bar": 2} initializes a map n using a map literal with two key-value pairs.
10. The output shows the value for "k1", the presence status of "k2", the contents of the map before and after deleting "k2", and the contents of the map initialized with literals.
Comments
Post a Comment