Iterating Over a Map with a Range and Applying a Function
This challenge focuses on effectively iterating over a Go map using the range keyword and applying a custom function to each key-value pair. Understanding how to process map elements is crucial for many Go programs, especially when dealing with data transformations or complex logic based on map contents.
Problem Description
You are tasked with writing a Go function that takes a map and a function as input. The map will contain string keys and integer values. The function you provide should accept a string (key) and an integer (value) as arguments and perform some operation on them. Your function should iterate over the map using the range keyword, calling your provided function for each key-value pair.
Key Requirements:
- The function must accept a map
map[string]intand a functionfunc(string, int). - The function must iterate over all key-value pairs in the map.
- For each key-value pair, the provided function must be called with the key and value as arguments.
- The function should not return any value. Its purpose is solely to execute the provided function for each map entry.
- The function should handle empty maps gracefully without panicking.
Expected Behavior:
The function should iterate through the map and execute the provided function for each key-value pair. The order of iteration is not guaranteed.
Edge Cases to Consider:
- Empty map: The function should not panic and should simply do nothing.
- Nil map: The function should not panic and should simply do nothing.
- Large maps: The function should be efficient enough to handle maps with a significant number of entries.
Examples
Example 1:
Input: map[string]int{"a": 1, "b": 2, "c": 3}, func(key string, value int) { fmt.Println(key, value) }
Output: (Prints to console) a 1, b 2, c 3 (order may vary)
Explanation: The function iterates over the map and prints each key-value pair to the console.
Example 2:
Input: map[string]int{}, func(key string, value int) { fmt.Println(key, value) }
Output: (No output)
Explanation: The map is empty, so the function does not iterate and nothing is printed.
Example 3: (Nil Map)
Input: nil, func(key string, value int) { fmt.Println(key, value) }
Output: (No output)
Explanation: The map is nil, so the function does not iterate and nothing is printed.
Constraints
- The map will always contain string keys and integer values.
- The provided function can perform any operation on the key and value.
- The map can contain up to 10,000 entries.
- The function should execute in O(n) time, where n is the number of entries in the map.
Notes
Consider using a closure if you need to access variables from the surrounding scope within the provided function. The range keyword provides a convenient way to iterate over maps in Go. Remember to handle nil and empty maps gracefully to prevent unexpected errors. Think about how you would test this function thoroughly to ensure it handles all possible scenarios.