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

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

如何將接口轉換為結構

如何將接口轉換為結構

Go
心有法竹 2023-06-19 13:44:40
這是緩存的簡化代碼。假設Container放在一個包里,所以它不知道Member。雖然我想在 Container 中存儲 Member 的實例,所以我在 Container 中存儲一個空的 Member 實例作為outerType. 在 中Container->GetMysql,我通過測試值填充一個新變量(但在現實世界中,它通過數據庫的數據動態填充)。然后在函數中Put,我將數據存儲在項目中作為緩存以供下次使用。在Get我得到存儲在項目中的數據。在此之前一切都很好。我的問題是我想將 Get 的結果轉換為 Member 的類型m = res.(Member)。我如何將它轉換為 Member 的實例我發現了很多關于這個主題的問題,但沒有一個解決了我的問題有關更多詳細信息:我想要Get返回數據及其在項目中存儲位置的指針。因此,如果我得到同一成員的一些變量,其中一個的變化會顯示在其他成員中package mainimport (    "fmt"    "reflect")type Member struct {    Id     int    Name   string    Credit int    Age    int}type Container struct {    outerType interface{}    items     map[string]*interface{}}func (cls *Container)GetMysql(s string, a int64) interface{}{    obj := reflect.New(reflect.TypeOf(cls.outerType))    elem := obj.Elem()    //elem := reflect.ValueOf(o).Elem()    if elem.Kind() == reflect.Struct {        f := elem.FieldByName("Name")        f.SetString(s)        f = elem.FieldByName("Credit")        f.SetInt(a)    }    return obj.Interface()}func (cls *Container)Get(value string) *interface{}{    return cls.items[value]}func (cls *Container)Put(value string, a int64) {    res := cls.GetMysql(value, a)    cls.items[value] = &res}func main() {    c := Container{outerType:Member{}}    c.items = make(map[string]*interface{})    c.Put("Jack", 500)    res := c.Get("Jack")    fmt.Println(*res)    m := &Member{}    m = res.(Member) // Here is the problem. How to convert ?    fmt.Println(m)}
查看完整描述

1 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

您幾乎不應該使用指向接口的指針。我的建議是永遠不要使用它,當你需要它時,你就會知道。


相反,如果你需要一個指向某物的指針(這樣你就可以在多個地方擁有相同的指針,因此在某處修改指向的值,它會對其他地方產生影響),在接口值中“包裝指針”。


因此,首先修改該items字段,使其存儲interface{}值而不是指針:


items map[string]interface{}

這意味著沒有限制:您可以傳遞和存儲指針,這不是問題。


接下來修改Get()返回interface{}:


func (cls *Container) Get(value string) interface{}{

    return cls.items[value]

}

并且在 中Put(),不要獲取以下地址interface{}:


func (cls *Container) Put(value string, a int64) {

    res := cls.GetMysql(value, a)

    cls.items[value] = res

}

并且您必須*Member根據 返回的值進行類型斷言Get()。


現在測試它:


c := Container{outerType: Member{}}

c.items = make(map[string]interface{})

c.Put("Jack", 500)

res := c.Get("Jack")

fmt.Println(res)

m := res.(*Member) // Here is the problem. How to convert ?

fmt.Println(m)

輸出(在Go Playground上嘗試):


&{0 Jack 500 0}

&{0 Jack 500 0}

現在,如果您要修改以下字段m:


m.Credit = 11

然后從緩存中獲取值:


fmt.Println(c.Get("Jack"))

我們將看到修改后的值,即使我們沒有調用(在Go PlaygroundPut()上嘗試):


&{0 Jack 11 0}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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