Home > Backend Development > Golang > How Can I Store and Invoke Functions Dynamically Using Maps in Go?

How Can I Store and Invoke Functions Dynamically Using Maps in Go?

Patricia Arquette
Release: 2024-12-12 21:43:09
Original
283 people have browsed it

How Can I Store and Invoke Functions Dynamically Using Maps in Go?

Storing Functions in a Map in Go

In Go, maps are versatile data structures that can store key-value pairs. Sometimes, it's useful to store functions in a map, allowing for dynamic invokation based on a key.

Problem:

Let's say you have multiple functions and want to create a map where the key is the function name and the value is the function itself. However, when attempting this as shown below, you encounter an error:

func a(param string) {}

m := map[string]func{} 
'a_func': a,
}

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

Solution:

The issue arises because the syntax for defining a type-specific map is incorrect. To resolve this, you can use the syntax map[string]interface{} instead, as type-safety is not enforced for the values. The modified example below illustrates how to store and invoke functions from the map:

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

In this example, the map m stores two function values as interface{}. When invoking the functions based on the key, a type assertion is performed to convert the interface value to the correct function type.

The above is the detailed content of How Can I Store and Invoke Functions Dynamically Using Maps 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