go - 如何调用 golang struct 字段的函数?

标签 go methods struct reflection

package main

import "fmt"
import "reflect"

type T struct{}

func (t *T) Foo() {
    fmt.Println("foo")
}

type A struct {
    Ts T
}

func main() {
    var t T
    var a A = A{Ts: t}
    val := reflect.ValueOf(&a).Elem()
    for i := 0; i < val.NumField(); i++ {
        vf := val.Field(i).Addr()
        fmt.Println(vf.Type())
        fmt.Println(vf.Kind())
        reflect.ValueOf(vf).MethodByName("Foo").Call([]reflect.Value{})
    }

}

$ go run reflect_call_1.go
*main.T ptr panic: reflect: call of reflect.Value.Call on zero Value

goroutine 1 [running]: reflect.flag.mustBe(0x0, 0x13)
/usr/local/go/src/reflect/value.go:201 +0xae reflect.Value.Call(0x0, 0x0, 0x0, 0xc420049f00, 0x0, 0x0, 0x0, 0x0, 0x40457c)
/usr/local/go/src/reflect/value.go:300 +0x38

最佳答案

vf 已经是 reflect.Value 类型,您不必将其传递给另一个 reflect.ValueOf()打电话。

只需调用 MethodByName()vf 上:

vf.MethodByName("Foo").Call([]reflect.Value{})

输出将是(在 Go Playground 上尝试):

*main.T
ptr
foo

关于go - 如何调用 golang struct 字段的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832854/

相关文章:

go - 将net.Dialer的超时设置和Connection的截止日期设置为相同的行为吗?

go - Cadence 长时间运行的子工作流程

xml - 在 Golang 中解码时如何获取 XML 标签的字符数据和属性值

java - 修改数组列表中元素的方法?

java - 枚举中的方法

C - 重新分配指针,它是结构 : dereferencing pointer to incomplete type 的属性

xml - 使用 Go 解码嵌套的 xml

ruby - 为什么我在此 Ruby 代码中收到 NoMethodError?

c++ - .txt 到 vector<struct> 故障

c++ - 将 const 结构引用转换为非常量指针