第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

Golang:有沒(méi)有一種方法可以使用反射以通用方式迭代切片?

Golang:有沒(méi)有一種方法可以使用反射以通用方式迭代切片?

Go
心有法竹 2023-02-21 16:48:23
有沒(méi)有一種方法可以使用反射以通用方式迭代切片?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}我想使用反射來(lái)降低代碼復(fù)雜性和重復(fù)代碼。這可能嗎?這是一個(gè)壞主意嗎?例如,不是這個(gè):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 回答

?
冉冉說(shuō)

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊

使用Value.LenValue.Index迭代數(shù)組或切片:

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

        }

    }

}


查看完整回答
反對(duì) 回復(fù) 2023-02-21
?
茅侃侃

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊

如果您的結(jié)構(gòu)執(zhí)行類(lèi)似的最終結(jié)果(返回 int 或?qū)ψ址M(jìn)行操作)但對(duì)于每種結(jié)構(gòu)類(lèi)型都是唯一的,您可以在它們上定義函數(shù):


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

}

然后定義一個(gè)接口Operable


type Operable interface {

    GetResult() int // shared function

}

然后創(chuàng)建一個(gè)接受接口作為參數(shù)的函數(shù),并且任何實(shí)現(xiàn)該接口中所有函數(shù)的結(jié)構(gòu)都可以作為參數(shù)被接受


func processOperable(o []Operable){

    for _, v := range o{

        v.GetResult() --> unique for each struct

    }

}


查看完整回答
反對(duì) 回復(fù) 2023-02-21
  • 2 回答
  • 0 關(guān)注
  • 134 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)