亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 136 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號