Home >Backend Development >Golang >How Can I Store Functions as Values in a Go Map?

How Can I Store Functions as Values in a Go Map?

DDD
DDDOriginal
2024-12-14 02:50:10176browse

How Can I Store Functions as Values in a Go Map?

Storing Functions in a Go Map

In Go, a map is a type that stores key-value pairs. Keys and values can be of any type. In your case, you want to store functions in a map. However, your code doesn't work because a function type cannot be used as a key in a map.

To work around this, you can use an interface type to represent a function. An interface type defines a set of methods that a type must implement to satisfy the interface. In this case, you can create an interface type that represents a function that takes a string as a parameter.

import "fmt"

// A function type that takes a string as a parameter.
type StringFunc func(string)

// A map that stores functions that take a string as a parameter.
var funcs map[string]StringFunc

// A function that takes a string as a parameter.
func a(p string) {
    fmt.Println("function a parameter:", p)
}

// Main function.
func main() {
    // Create a map that stores functions that take a string as a parameter.
    funcs = make(map[string]StringFunc)

    // Add the 'a' function to the map.
    funcs["a"] = a

    // Call the 'a' function from the map.
    funcs["a"]("hello")
}

The above is the detailed content of How Can I Store Functions as Values in a Go Map?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn