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

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

go - 寫入接口的函數(shù){}

go - 寫入接口的函數(shù){}

Go
守候你守候我 2021-11-01 15:18:05
我想將指向某個東西的指針傳遞給一個函數(shù),而在編譯時不知道它的類型,讓函數(shù)寫入它。這是我認為可行的方法:func foo(dest interface{}) {    switch (dest).(type) {    case *int:        fmt.Println("got int")        *dest = 1    // handle other cases...    }}但是,使用*int輸入調用它func main() {    bar := 2    foo(&bar)    fmt.Println(bar) // expect 1}產(chǎn)生編譯器錯誤invalid indirect of dest (type interface {}).我在這里做錯了什么?
查看完整描述

3 回答

?
神不在的星期二

TA貢獻1963條經(jīng)驗 獲得超6個贊

在這段代碼中(順便說一句,您不需要周圍的括號dest),一旦輸入案例,您基本上會忘記類型:


func foo(dest interface{}) {

    switch dest.(type) {

    case *int:

        fmt.Println("got int")

        *dest = 1

    // handle other cases...

    }

}

也就是說,根據(jù)編譯器, dest 仍然是 interface{} 類型,這是*dest = 1錯誤的。


你可以使用更多這樣的類型斷言......


func foo(dest interface{}) {

    switch dest.(type) {

    case *int:

        fmt.Println("got int")

        *dest.(*int) = 1

        // handle other cases...

    }

}

...但實際上“記住”類型的開關會好得多(來自Effective Go)


func foo(dest interface{}) {

    switch dest := dest.(type) {

    case *int:

        fmt.Println("got int")

        *dest = 1

    // handle other cases...

    }

}


查看完整回答
反對 回復 2021-11-01
?
楊__羊羊

TA貢獻1943條經(jīng)驗 獲得超7個贊

dest 仍然是類型interface{}。您還必須在分配期間投射它:

*dest.(*int) = 1


查看完整回答
反對 回復 2021-11-01
?
富國滬深

TA貢獻1790條經(jīng)驗 獲得超9個贊

這個問題似乎有點老了,但我提出了一種使用反射來處理這個問題的更通用的方法,它不如其他解決方案快,但它適用于您傳遞給函數(shù)的任何其他類型


func foo(dest interface{}) {

    destVal := reflect.ValueOf(dest)

    val := reflect.ValueOf(1)

    if destVal.Kind() == reflect.Ptr && destVal.Elem().Kind() == val.Kind() {

        if destElem := destVal.Elem(); destElem.CanSet() {

            destElem.Set(val)

        }

    }

}



查看完整回答
反對 回復 2021-11-01
  • 3 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號