在 Go 中按名称调用结构体方法
该查询涉及通过指定名称来调用 Go 结构体上的方法。与提供的 MethodByName() 函数不同,OP 设想了一种更直接的方法。
实现请求
要实现此目的,请使用以下步骤:
示例实现:
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) }
输出:
My statement
注意: MethodByName () 函数接受表示方法名称的字符串参数。
以上是如何使用反射按名称调用 Go Struct 方法?的详细内容。更多信息请关注PHP中文网其他相关文章!