为结构字段分配一个接口。

huangapple go评论86阅读模式
英文:

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 &lt; 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

huangapple
  • 本文由 发表于 2022年7月26日 00:00:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/73112182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定