给定
type Runnable interface {
Run()
}
type T struct {
Z struct {
A int
}
}
func (t T) Run() {
t.Z.A = 1
}
func main() {
t := reflect.TypeOf( T{} )
var v reflect.Value
v = reflect.New(t).Elem()
runnable := v.Interface().(Runnable)
runnable.Run()
最后,有没有办法检索 Z 及其由 Run()
方法设置的字段值?
我正在实现一个 API 命令模式,所以 T
可以是 RegisterCommand
、LoginCommand
、LogoutCommand
等。 Z 是“输出文档”——API 命令返回的 JSON 文档——我想以声明方式指定,并在命令运行后写入网络。
最佳答案
明白了!感谢 synful 的“指针”:-)
z := v.Elem().FieldByName("Z").Interface()
关于reflection - 如何从 refect.Value 获取结构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27362529/