簡體   English   中英

go-寫入接口的功能{}

[英]go - function to write to an interface{}

我想將指向某物的指針傳遞到函數中,而在編譯時不知道其類型,請將該函數寫入其中。 這是我認為可行的方法:

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
}

產生編譯器錯誤

invalid indirect of dest (type interface {})

我在這里做錯了什么?

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

func foo(dest interface{}) {
    switch dest.(type) {
    case *int:
        fmt.Println("got int")
        *dest = 1
    // handle other cases...
    }
}

也就是說,根據編譯器,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...
    }
}

dest仍然是interface{}類型。 您還必須在作業期間強制轉換:

*dest.(*int) = 1

這個問題似乎有點老了,但是我已經找到了一種使用反射來處理此問題的更通用的方法,它的速度不如其他解決方案快,但可以與您傳遞給函數的任何其他類型一起使用

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)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM