有没有办法使用反射设置接口字段?当我尝试设置它时,它惊慌失措地说该值不可寻址。
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)
相关分类