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

How Can I Assign and Call Functions as Values in a Go Map?

Susan Sarandon
Release: 2024-12-09 18:34:15
Original
795 people have browsed it

How Can I Assign and Call Functions as Values in a Go Map?

Assigning Functions to Keys in a Go Map

In Go, you can define custom functions and assign them as values to keys in a map. This allows for dynamic execution of functions based on a given key.

To achieve this, you can create a map of type map[string]func(...) where the key is a string and the value is a function. However, the provided code attempts to use a syntax that is not supported in Go.

To fix this, use the following code:

func a(param string) {
    fmt.Println("Function a called with param:", param)
}

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

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

In this example:

  • The map[string]func(string) declares a map with string keys and functions that take a single string argument.
  • The m variable initializes a map with a key "a_func" and a value that is a reference to the a function.
  • The range loop iterates over the map, calling the function associated with the "a_func" key and passing "test" as an argument.

Note that the interface{} type in the provided code example is not necessary and can be simplified to func(...).

The above is the detailed content of How Can I Assign and Call Functions as Values in a Go Map?. 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