I am new to type safe, and can't figure out how to do following
package main
func test(){
print("In Test")
}
func main(){
a := "test"
a()
}
I am new to type safe, and can't figure out how to do following
package main
func test(){
print("In Test")
}
func main(){
a := "test"
a()
}
You might get better answers if you state what you're trying to achieve, as reflection is usually not the best way. But reflect will help if the functions are methods on a type (net/rpc is an example of this).
package main
import (
"fmt"
"reflect"
)
type T struct {}
func (T) Add(x, y int) int {
return x + y
}
func main() {
t := reflect.ValueOf(T{})
m := t.MethodByName("Add")
args := []reflect.Value{reflect.ValueOf(1), reflect.ValueOf(2)}
fmt.Println(m.Call(args)[0].Int())
}
If you were wondering how tools like godoc work, they parse the source rather than use reflection.
Edit: Playground version
A function can not be resolved from a string. However, you can assign a function to a variable.
a := test
a()
You can also put functions (assuming they all have the same signature) into a map:
var func_map := map[string]func() {
"test": test,
}
a := func_map["test"]
a()
Response to first comment by OP (too long to make another comment):
They don't all have the same signature
If they don't all have the same signature, how do you plan to call them? You could use the reflect
package, but that is normally an indication that you are doing something wrong.
This is not a dynamic language and some things can not be done in Go. Although, they are mostly things you should not do in most languages anyways.
There's no way to dynamically look up a function by name, but I think it's worth mentioning why. Basically, the reason is so that the compiler and/or linker can eliminate unused functions.
Consider that if you were able to get a function by name, then every function in every imported package (recursively) would have to be linked into the final executable, even if it was never used, just in case someone wanted to look it up by name. People already complain about the large size of Go binaries, but this would cause them to be much larger still.
© 2022 - 2024 — McMap. All rights reserved.