英文:
Assign an interface to a struct field
问题
考虑到我们有一个接口的聚合结构体:
type Aggregation struct {
a InterfaceA
b InterfaceB
...
n InterfaceN
}
我们试图通过使用反射来使下面的函数更加灵活,以消除 switch 语句:
func (a *Aggregation) Register(i interface{}) *Aggregation {
switch v := i.(type) {
case InterfaceA:
a.a = v
case InterfaceB:
a.a = b
...
case InterfaceN:
a.a = v
}
return a
}
有没有办法使用反射来实现相同的功能呢?
英文:
Consider we have an aggregation struct of interfaces
type Aggregation struct {
a InterfaceA
b InterfaceB
...
n InterfaceN
}
we are trying to make the following function to initialize this struct's fields more funky -- to eliminate the switch:
func (a *Aggregation) Register(i interface{}) *Aggregation {
switch v := i.(type) {
case InterfaceA:
a.a = v
case InterfaceB:
a.a = b
...
case InterfaceN:
a.a = v
}
return a
}
is there any way to accomplish the same functionality with reflection?
答案1
得分: 1
这似乎正在工作
func (a *Aggr) Register2(i interface{}) *Aggr {
v := reflect.ValueOf(a).Elem()
for j := 0; j < v.NumField(); j++ {
f := v.Field(j)
t := f.Type()
if reflect.TypeOf(i).Implements(t) {
f.Set(reflect.ValueOf(i))
break
}
}
return a
}
cc @jimb
英文:
This seems to be working
func (a *Aggr) Register2(i interface{}) *Aggr {
v := reflect.ValueOf(a).Elem()
for j := 0; j < v.NumField(); j++ {
f := v.Field(j)
t := f.Type()
if reflect.TypeOf(i).Implements(t) {
f.Set(reflect.ValueOf(i))
break
}
}
return a
}
cc @jimb
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论