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

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

如何獲取 interface{} 參數以指向其他內容?

如何獲取 interface{} 參數以指向其他內容?

Go
慕容森 2021-07-02 10:02:03
如何進行以下工作并進行輸出"Result is: [Value from GetFromMemory]."?不幸的是我無法改變的方法簽名GetItem和Get。http://play.golang.org/p/R5me3Q3y4Wpackage mainimport "fmt"type Key stringtype Item struct {    Key   Key    Value string}func GetItem(key Key) interface{} {    return &Item{key, "Value from GetFromMemory"}}// How can I make item point to the one created in GetItem?func Get(key Key, item interface{}) {    item = GetItem(key)}func main() {    var item Item    Get("Key1", &item)    // This should print "Result is: [Value from GetFromMemory]."    fmt.Printf("Result is: [%s].", item.Value)}
查看完整描述

1 回答

?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

當您處理interface{}值時,您需要類型斷言或反射。


如果您知道要處理哪些類型,則類型斷言可能是可行的方法(代碼運行):


func GetItem(key Key) interface{} {

    return &Item{key, "Value from GetFromMemory"}

}


func Get(key Key, item interface{}) {

    switch v := item.(type) {

        case **Item:

            *v = GetItem(key).(*Item)

    }

}


// Usage:

var item *Item

Get("Key1", &item)

中的代碼Get已布局,以便您可以輕松地為更多類型添加更多條件。該類型的開關檢查的基礎類型的item。在這種情況下,它是一個指向 an 的指針Item(它*Item在 main 中,然后我們給出Get了 的地址&item,使其成為 a **Item)。


在類型匹配時匹配的部分中,我們可以調用GetItem,斷言結果對象的類型*Item并將其復制到*v。


請注意,當您在 中生成指針值時,我將item變量更改*Item為GetItem,因此獲取指針而不是Item對象的副本更有意義。


另請注意,您需要檢查類型斷言的結果,例如用于從 中檢索值的斷言GetItem。如果您不這樣做并且類型不匹配,例如*Item,您的代碼將因運行時恐慌而崩潰。


檢查類型斷言:


v, ok := someInterfaceValue.(SomeType)

// ok will be true if the assertion succeeded

為了完整起見,您也可以使用反射來解決您的問題。定義Get如下(播放示例):


func Get(key Key, item interface{}) {

    itemp := reflect.ValueOf(item).Elem()

    itemp.Set(reflect.ValueOf(GetItem(key)))

}

發生的情況是,首先item(type **Item)的反射值被取消引用,假設它是一個指針值,給我們一個 type 的反射值*Item。然后GetItem通過使用該Set方法將所述值設置為的反映值。


當然,您需要檢查類型item是否實際上是指針。不這樣做并傳遞非指針值Get將導致恐慌。


查看完整回答
反對 回復 2021-07-05
  • 1 回答
  • 0 關注
  • 359 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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