Home > Backend Development > Golang > How Can I Map Functions with Different Signatures in Go?

How Can I Map Functions with Different Signatures in Go?

Mary-Kate Olsen
Release: 2024-12-10 22:15:14
Original
858 people have browsed it

How Can I Map Functions with Different Signatures in Go?

Mapping Functions in Go

In Go, maps provide a powerful way to associate keys with their respective values. To map functions, the key is typically a string representing the name or identifier of the function, while the value is a function reference.

Example:

Consider the following Go program:

func a(param string) {
    fmt.Println("parameter:", param)
}

m := map[string]func(string) {
    "a": a,
}

for key, value := range m {
    if key == "a" {
        value("hello")
    }
}
Copy after login

In this example, a map m is used to store a mapping between the string key "a" and the function reference a. The loop iterates over the map and executes the function associated with the "a" key, passing in the string "hello" as an argument.

Handling Varied Function Signatures:

However, in your initial attempt, you encountered an issue when trying to store functions with different signatures in the map. This is because the value type in the map is declared as func(). To handle functions with varying signatures, we can use an interface as the value type, such as the interface{} used in the following revised example:

func f(p string) {}
func g(p string, q int) {}

m := map[string]interface{}{
    "f": f,
    "g": g,
}
for k, v := range m {
    switch k {
    case "f":
        v.(func(string))("astring") // Explicit cast to type func(string)
    case "g":
        v.(func(string, int))("astring", 42) // Explicit cast to type func(string, int)
    }
}
Copy after login

By using the interface{} type, we allow the map to store values of any type, including functions with different signatures. We then use explicit type casting within the loop to execute the functions with their respective parameters.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template