Maps are key-value pairs, and range provides a convenient way to iterate over all the entries in a map. Unlike slices, when you range over a map, you get the key and value for each entry.
When you use range with a map, it returns two values on each iteration: the key and the value.
ages := map[string]int{
"Goku": 30,
"Vegeta": 35,
"Gohan": 20,
}
for name, age := range ages {
fmt.Println(name, "is", age, "years old")
}
// Output (order may vary):
// Goku is 30 years old
// Vegeta is 35 years old
// Gohan is 20 years old
The first variable receives the key, and the second receives the value associated with that key.
Unlike slices, maps in Go do not maintain any order. Each time you iterate over a map, the entries may appear in a different order:
powerLevels := map[string]int{
"Goku": 9000,
"Vegeta": 8500,
"Gohan": 8000,
}
// First iteration might print:
// Vegeta: 8500
// Gohan: 8000
// Goku: 9000
// Second iteration might print:
// Goku: 9000
// Vegeta: 8500
// Gohan: 8000
This is intentional - Go randomizes map iteration order to prevent developers from relying on it. If you need a specific order, you must sort the keys yourself.
You can ignore the values by using the blank identifier _:
capitals := map[string]string{
"USA": "Washington D.C.",
"Japan": "Tokyo",
"France": "Paris",
}
for country := range capitals {
fmt.Println(country)
}
// Prints just the keys (order may vary):
// USA
// Japan
// France
Or simply omit the second variable:
for country := range capitals {
fmt.Println("Country:", country)
}
To iterate over just the values, you need to use the blank identifier for the key:
scores := map[string]int{
"Alice": 95,
"Bob": 87,
"Carol": 92,
}
for _, score := range scores {
fmt.Println("Score:", score)
}
// Prints just the values (order may vary):
// Score: 95
// Score: 87
// Score: 92
You can use the keys to modify values in the map:
inventory := map[string]int{
"apples": 10,
"bananas": 5,
"oranges": 8,
}
for item, quantity := range inventory {
if quantity < 7 {
inventory[item] = quantity + 10 // Restock
fmt.Println("Restocked", item)
}
}
Ranging over an empty map is safe - the loop simply won't execute:
empty := map[string]int{}
for key, value := range empty {
fmt.Println(key, value) // Never executes
}
fmt.Println("Done!") // This runs normally
For this challenge, create a function called findStrongest that accepts a parameter powerLevels (a map with string keys and int values: map[string]int).
The function should:
range to iterate over the map"[name] is the strongest with [powerLevel]"The function signature is:
func findStrongest(powerLevels map[string]int) {
// Your code here
}
For example, calling findStrongest(map[string]int{"Goku": 9001, "Vegeta": 8500, "Gohan": 8000}) should print:
Goku is the strongest with 9001