有没有办法使用反射设置接口字段?当我尝试设置它时,它惊慌失措地说该值不可寻址。type A interface{...}func CreateA(name string) A {...}type B struct { field A should A mirror A}// normal way of initializingvar 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 likevar b = &B{}MirrorField(b)
1 回答
- 1 回答
- 0 关注
- 149 浏览
添加回答
举报
0/150
提交
取消