Junior — Middle
Is it possible to pass a function as a value in a map data structure?
sobes.tech AI
Answer from AI
Yes, in Go, functions can be passed as values in data structures like map, since functions are first-class citizens.
Example:
package main
import "fmt"
func main() {
// Declare a map with string keys and function values that take an int and return an int
funcMap := make(map[string]func(int) int)
// Add functions to the map
funcMap["square"] = func(x int) int { return x * x }
funcMap["double"] = func(x int) int { return x * 2 }
// Use functions from the map
fmt.Println(funcMap["square"](5)) // 25
fmt.Println(funcMap["double"](5)) // 10
}
Thus, you can store and call functions from a map by key.