Home >Backend Development >Golang >How Can I Call a Go Function Using Its Name (String) at Runtime?

How Can I Call a Go Function Using Its Name (String) at Runtime?

DDD
DDDOriginal
2024-12-04 18:45:14264browse

How Can I Call a Go Function Using Its Name (String) at Runtime?

Pointer to Function from String in Go

Metaprogramming, or the ability to manipulate code itself at runtime, is a powerful technique in programming. In Go, one aspect that may arise is the need to access a pointer to a function based on its name, which is provided as a string.

Solution

Unlike dynamic languages, Go functions are considered first-class values. This means that functions can be passed as arguments to other functions, eliminating the need for complex metaprogramming techniques.

To demonstrate this, consider the following code snippet:

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))
}

Execution

When this code is executed, it will produce the following output:

123
99

This demonstrates how functions can be passed as arguments to someOtherFunction, based on their names.

Custom Function Selection

If the selection of the function depends on a value that is only known at runtime, you can use a map to associate function names with their corresponding function pointers:

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 Can I Call a Go Function Using Its Name (String) at Runtime?. 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