Answer the question
In order to leave comments, you need to log in
Call a function with the name of the function in a string?
Good afternoon.
How can you call a function knowing the name of the function? Those. the string variable contains the name of this function. Is it possible?
func f(){
fmt.Println("функция вызвана")
}
func main(){
str = "f"
вызвать_функцию(str)
}
Answer the question
In order to leave comments, you need to log in
In general, no.
https://mikespook.com/2012/07/function-call-by-nam...
You can only organize it through the ass. Stifler 's dad in a nearby answer showed how. A lot of reflection in the example code and shows that this is the wrong way. Only as a last resort.
And here is a thing that does not contradict the ideology of Go - it will be with an explicit indication of types:
package main
import (
"fmt"
)
func add(a, b int) int {
return a + b
}
func sub(a, b int) int {
return a - b
}
func main() {
table:= make(map[string]func(int,int)int)
table["func1"] = add
table["func2"] = sub
fmt.Println(table["func1"](5, 3))
fmt.Println(table["func2"](5, 3))
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question