为了账号安全,请及时绑定邮箱和手机立即绑定

Golang:有没有一种方法可以使用反射以通用方式迭代切片?

Golang:有没有一种方法可以使用反射以通用方式迭代切片?

Go
心有法竹 2023-02-21 16:48:23
有没有一种方法可以使用反射以通用方式迭代切片?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        }    }}
查看完整描述

2 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

使用Value.LenValue.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

        }

    }

}


查看完整回答
反对 回复 2023-02-21
?
茅侃侃

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

    }

}


查看完整回答
反对 回复 2023-02-21
  • 2 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号