【发布时间】:2015-02-18 19:53:23
【问题描述】:
有没有办法使用反射设置接口字段?当我尝试设置它时,它惊慌地说该值不可寻址。
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)
【问题讨论】:
-
你会反思什么?上面的代码编译得很好。你有什么问题?
-
为此,通常使用type assertion。你想用反射做什么?
标签: reflection go