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

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

如何將未編組的 Golang 對象轉換為指定變量的類型

如何將未編組的 Golang 對象轉換為指定變量的類型

Go
肥皂起泡泡 2021-08-23 17:46:23
我想將各種對象編組到文件中,然后解組它們,并通過獲取編組的變量的類型將它們轉換回原始類型。關鍵是我想將未編組的對象轉換為指定變量的類型,而不指定類型。簡短的偽代碼:// Marshal thisitem := Book{"The Myth of Sisyphus", "Albert Camus"}// Then unmarshal and convert to the type of the item variable.itemType := reflect.TypeOf(item)newItem itemType = unmarshalledItem.(itemType)  // This is the problem.fmt.Println("Unmarshalled is:", reflect.TypeOf(newItem)) // Should print *main.Book完整代碼:package mainimport (    "encoding/json"    "fmt"    "io/ioutil"    "os"    "reflect")type Book struct {    Title  string    Author string}func main() {    // Create objects to marshal.    book := Book{"The Myth of Sisyphus", "Albert Camus"}    box := make(map[string]interface{})    box["The Myth of Sisyphus"] = &book    itemType := reflect.TypeOf(box["The Myth of Sisyphus"])    fmt.Println("Book is:", itemType)    // Marshal objects to file.    err := Write(&book)    if err != nil {        fmt.Println("Unable to save store.", err)        return    }    // Unmarshal objects from file.    untyped := make(map[string]interface{})    bytes, err := ioutil.ReadFile("store.txt")    if err != nil {        fmt.Println("Unable to load store.", err)        return    }    err = json.Unmarshal(bytes, &untyped)    if err != nil {        fmt.Println("Err in store unmarshal.", err)        return    }    // Get Title property of unmarshalled object,    // and use that to get variable type from box map.    for k, v := range untyped {        if k == "Title" {            itemTitle := v.(string)            fmt.Println("Cast item having title:", itemTitle)            targetType := reflect.TypeOf(box[itemTitle])            fmt.Println("Type to cast to is:", targetType)            // Convert untyped to targetType.            // This is the problem.            typed targetType = untyped.(targetType)            fmt.Println("Unmarshalled is:", reflect.TypeOf(typed)) // Should print *main.Book        }    }}
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 220 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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