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

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

方法如何獲取接口類型的輸出參數(shù)?

方法如何獲取接口類型的輸出參數(shù)?

Go
慕勒3428872 2023-06-12 16:32:08
鑒于:type Savable interface {}type Customer struct {} // satisfies 'Savable'func GetSaved(id string, s Savable) {? // somehow get a reference to the object from cache? s = cachedObject?? // alternately, something like:? // json.Unmarshal(jsonFromDisk, &s)}func Foo() {? c := Customer{}? GetSaved("bob", &c)}嘗試一些配置后,我得到與“Expects *Savable, found *Customer”相關的編譯錯誤,或者該GetSaved函數(shù)實際上并沒有改變我想要成為“輸出變量”的內(nèi)容。這可行嗎,我只是沒有得到正確的接口/指針/等組合?或者由于某種原因這是不可能的?
查看完整描述

2 回答

?
泛舟湖上清波郎朗

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

您可以使用反射來設置傳遞的接口。即使將結構引用作為接口傳遞,底層類型信息也不會丟失,我們可以使用反射。


package main


import (

    "fmt"

    "reflect"

)


type Savable interface {}


type Customer struct {

    Name string


func GetSaved(id string, s Savable) {

    cached := Customer{ Name: id }

    c1 := reflect.ValueOf(cached)

    reflect.ValueOf(s).Elem().Set(c1)

}


func main() {

  c := Customer{}

  fmt.Printf("Before: %v\n", c)

  GetSaved("bob", &c)

  fmt.Printf("After: %v\n", c)

}

這是運行鏈接


查看完整回答
反對 回復 2023-06-12
?
繁花不似錦

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

這有效,我將它轉換為字節(jié)并將其解組回您的結構。希望這可以幫助。:) 包主要


import (

    "encoding/json"

    "fmt"

)


type Savable interface{}

type Customer struct {

    Name string

} // satisfies 'Savable'


func GetSaved(id string, s Savable) {

    // somehow get a reference to the object from cache

    cached := Customer{Name: "Bob"}

    byt, _ := json.Marshal(cached)


    _ = json.Unmarshal(byt, &s)


}


func main() {

    c := Customer{}

    GetSaved("bob", &c)

    fmt.Println(c)

}

運行鏈接: https: //play.golang.org/p/NrBRcRmXRVZ


查看完整回答
反對 回復 2023-06-12
  • 2 回答
  • 0 關注
  • 203 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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