2 回答
TA贡献1877条经验 获得超1个赞
使用Value.Len和Value.Index迭代数组或切片:
func processData(l LotsOfSlices) {
v := reflect.ValueOf(l)
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if f.Kind() != reflect.Slice {
continue
}
for i := 0; i < f.Len(); i++ {
e := f.Index(i)
s := e.FieldByName("F")
// Do something with s
}
}
}
TA贡献1842条经验 获得超22个赞
如果您的结构执行类似的最终结果(返回 int 或对字符串进行操作)但对于每种结构类型都是唯一的,您可以在它们上定义函数:
func (a *A) GetResult() int { // sums two numbers
return a.p1 + a.p2
}
func (b *B) GetResult() int { // subtracts two numbers
return b.p1 - b.p2
}
func (c *C) GetResult() int { // times two numbers
return c.p1 * c.p2
}
然后定义一个接口Operable
type Operable interface {
GetResult() int // shared function
}
然后创建一个接受接口作为参数的函数,并且任何实现该接口中所有函数的结构都可以作为参数被接受
func processOperable(o []Operable){
for _, v := range o{
v.GetResult() --> unique for each struct
}
}
- 2 回答
- 0 关注
- 160 浏览
添加回答
举报
