1. Introduction
Maps in Go are a key-value data structure used to hold related data pairs. Adding or updating elements in a map is a frequent operation when working with this data type. This post will explore how to perform these operations in Go, with examples.
Definition
In Go, a map is a data type that associates keys with values. If a key already exists in the map, assigning a new value to it updates the key with that value. If the key does not exist, the assignment adds the new key-value pair to the map.
2. Program Steps
1. Declare and initialize a map.
2. Add new elements to the map.
3. Update existing elements in the map.
4. Verify the additions and updates by printing the map.
3. Code Program
package main
import "fmt"
func main() {
// Step 1: Declare and initialize a map
userAges := make(map[string]int)
// Step 2: Add new elements to the map
userAges["Alice"] = 28
userAges["Bob"] = 25
// Add another element to demonstrate the update
userAges["Charlie"] = 30
// Step 3: Update an existing element in the map
userAges["Alice"] = 29 // Alice had a birthday!
// Step 4: Print the map to verify additions and updates
for name, age := range userAges {
fmt.Printf("%s is %d years old\n", name, age)
}
}
Output:
Alice is 29 years old Bob is 25 years old Charlie is 30 years old
Explanation:
1. package main - The package declaration for the Go program.
2. import "fmt" - Imports the Format package necessary for printing to the console.
3. userAges is a map from strings to ints, initialized with make.
4. New key-value pairs are added to userAges for Alice, Bob, and Charlie, representing their ages.
5. The value for Alice is then updated to 29, simulating a change in her age.
6. A for loop with the range operator is used to iterate over the map and print each key-value pair, showing the ages of the users.
7. The output verifies that Alice's age has been updated to 29, and two new elements have been added for Bob and Charlie.
Comments
Post a Comment