Home >Backend Development >Golang >How Can I Call a Go Struct Method by Its Name Using Reflection?
Invoking Struct Methods by Name in Go
The query pertains to calling a method on a Go struct by specifying its name. Unlike the provided MethodByName() function, the OP envisions a more direct approach.
Implementing the Request
To accomplish this, utilize the following steps:
Example Implementation:
package main import "fmt" import "reflect" type MyStruct struct {} func (p *MyStruct) MyMethod() { fmt.Println("My statement") } func main() { var s MyStruct reflect.ValueOf(&s).MethodByName("MyMethod").Call(nil) }
Output:
My statement
Note: The MethodByName() function accepts a string argument representing the method's name.
The above is the detailed content of How Can I Call a Go Struct Method by Its Name Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!