有没有一种方法可以使用反射以通用方式迭代切片?
type LotsOfSlices struct {
As []A
Bs []B
Cs []C
//.... and lots more of these
}
type A struct {
F string
//.... and lots of other stufff that's different from the other structs
}
type B struct {
F string
//.... and lots of other stufff that's different from the other structs
}
type C struct {
F string
//.... and lots of other stufff that's different from the other structs
}
我想使用反射来降低代码复杂性和重复代码。这可能吗?这是一个坏主意吗?
例如,不是这个:
func processData(l LotsOfSlice){
for _, a := range l.As{
// use a.F
}
for _, b := range l.Bs{
// use b.F
}
for _, c := range l.Cs{
// use c.F
}
...
}
但是这样的事情:
func processData(l LotsOfSlices){
t := reflect.TypeOf(l)
for i := 0; i < t.NumField(); i++ {
zs := reflect.ValueOf(l).Field(i).Interface()
for _, z := range zs{
// use z.F
}
}
}
冉冉说
茅侃侃
相关分类