是否可以使用反射设置界面字段?当我尝试设置它时,它惊慌地说该值不可寻址.
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.
您的代码的有效示例: play.golang/p/Mf1HENRSny
A working example of your code: play.golang/p/Mf1HENRSny
更多推荐
使用接口的字段类型设置结构字段
发布评论