Home > Backend Development > Golang > How to Correctly Define and Use a Map of Functions in Go?

How to Correctly Define and Use a Map of Functions in Go?

Barbara Streisand
Release: 2024-12-17 19:03:10
Original
889 people have browsed it

How to Correctly Define and Use a Map of Functions in Go?

Go Map of Functions

Mapping functions to string keys can be a useful tool for organizing and selecting methods in Go. However, a common hurdle is ensuring the correct syntax and typing. Let's explore how to define and utilize a map of functions effectively in Go.

The provided code attempts to create a map with a string key pointing to a function. However, the syntax used in m := map[string] func {...} is incorrect. To define a map of function pointers, the correct syntax is m := map[string]interface{}{...}.

Furthermore, the use of single quotes '' for map keys is not valid. Double quotes "" should be used for string keys.

To demonstrate a working example, consider the following code:

package main

import "fmt"

func f(p string) {
    fmt.Println("function f parameter:", p)
}

func g(p string, q int) {
    fmt.Println("function g parameters:", p, q)
}

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

Here, a map m is created, where each key is a string, and the corresponding value is a function pointer. The switch statement checks the key and casts the value to the appropriate function type before calling the function with the desired parameters. This approach allows for dynamic function selection and execution based on the provided key.

The above is the detailed content of How to Correctly Define and Use a Map of Functions 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