使用接口的字段类型设置结构字段 [英] Set a struct field with field type of a interface

查看:46
本文介绍了使用接口的字段类型设置结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用反射设置界面字段?当我尝试设置它时,它惊慌地说该值不可寻址.

Is there any way to set an interface field using reflect? When i tried to set it, it paniced saying that the value is non addressable.

type A interface{...}

func CreateA(name string) A {...}

type B struct {
   field A
   should A
   mirror A
}

// normal way of initializing
var b = B{
  field: CreateA("field"),
  should: CreateA("should"),
  mirror: CreateA("mirror"),
}

func MirrorField(b *B) {
   t := reflect.TypeOf(b)
   v := reflect.ValueOf(b)
   for i := 0; i < t.NumField(); i++ {
      setTo = CreateA(t.Field(1).Name)
      fieldVal := v.Field(i)
      fieldVal.Set(reflect.ValueOf(setTo))
   }
}

// what i want is something like
var b = &B{}
MirrorField(b)

推荐答案

接口没有字段,它们仅定义包含它们的值的方法集.在界面上进行反射时,可以使用 Value.Elem() .

Interfaces don't have fields, they only define a method set of the value they contain. When reflecting on an interface, you can extract the value with Value.Elem().

您也不能设置未导出的字段.您需要将 B 类型的字段名称大写.遍历字段时,请使用 Value.CanSet() 测试它们是否可设置. CanSet()还将返回false,因为该值不可寻址,或者该值仍在接口中.

You also can't Set unexported fields. You need to capitalize the field names in your B type. When iterating over the fields, use Value.CanSet() to test if they are settable. CanSet() will also return false is the value isn't addressable, or the value is still in an interface.

您的代码的有效示例: http://play.golang.org/p/Mf1HENRSny

A working example of your code: http://play.golang.org/p/Mf1HENRSny

这篇关于使用接口的字段类型设置结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆