Home >Backend Development >Golang >How to Dynamically Invoke Go Functions Using String Names?

How to Dynamically Invoke Go Functions Using String Names?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 20:41:14765browse

How to Dynamically Invoke Go Functions Using String Names?

Invoking Functions Dynamically Using String Names in Go

In Go, functions occupy a first-class position, eliminating the need for circuitous techniques employed in dynamic languages. This allows functions to be passed as parameters to other functions, effectively enabling metaprogramming capabilities.

For instance, suppose you want to pass a function as an argument to another function. Here's the code you can use to accomplish this:

package main

import "fmt"

func someFunction1(a, b int) int {
        return a + b
}

func someFunction2(a, b int) int {
        return a - b
}

func someOtherFunction(a, b int, f func(int, int) int) int {
        return f(a, b)
}

func main() {
        fmt.Println(someOtherFunction(111, 12, someFunction1))
        fmt.Println(someOtherFunction(111, 12, someFunction2))
}

Running this code will produce the following output:

123
99

Furthermore, if the function selection is influenced by a runtime-only known value, a map can be utilized:

m := map[string]func(int, int) int {
        "someFunction1": someFunction1,
        "someFunction2": someFunction2,
}

...

z := someOtherFunction(x, y, m[key])

The above is the detailed content of How to Dynamically Invoke Go Functions Using String Names?. 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