登录
首页 >  Golang >  Go问答

不能在映射结构中调用外部结构

来源:stackoverflow

时间:2024-03-19 23:09:33 157浏览 收藏

在 Go 中,将 JSON 解组到包含外部结构的映射结构中时,可能会遇到问题。如果外部结构位于其他包中,则反序列化可能会失败,导致默认结构值加载到映射中。一种解决方法是创建一个新的本地类型,继承外部结构,但这可能存在限制。因此,需要找到一种更优雅的方法来解决这个问题。

问题内容

我一直在努力找出在解组 json 时调用 map[string]struct 类型的外部结构的正确方法。

当代码全部位于同一个包中时,代码可以工作,但是如果它拉出导出类型,则 unmarshal 函数似乎会出现错误。

package animals

type bird struct {
    name        string `json:"name"`
    description string `json:"description"`
}
package main

import (
    "encoding/json"
    "fmt"

    "../animal"
)

func main() {
    birdJson := `{"birds":{"name":"eagle","description":"bird of prey"}}`
    var result map[string]animals.Bird //If Bird is external (animals.Bird) then the Unmarshal breaks
    json.Unmarshal([]byte(birdJson), &result)

    birds := result["birds"]
    fmt.Printf("%s: %s", birds.Name, birds.Description) 
    // These entries will be the struct defaults instead of the values in birdJson
}

https://play.golang.org/p/e4fgifath4s

所以上面的代码工作正常,但如果 type bird struct{} 是从另一个包导入的,那么当我设置 map[string]animals.bird 时,json.unmarshal 不起作用。

我发现的解决方法是设置一个新类型,如下所示: type 鸟类动物。bird。有更优雅的方法吗?

如果未来的函数需要原始的 animal.bird struct 并且在尝试使用我的新本地类型时会出错,这将成为一个更大的问题。

更新: 我已经更新了上面的代码以显示非工作示例。问题是值不会正确加载到 map[string]animals.bird 中,而是加载默认的结构值。我必须使用本地包结构来正确解组值。


解决方案


抱歉,上面的代码有效,事实证明它是流氓的一部分 func (e *Bird) UnmarshalJSON(b []byte) error {} 我在这上面浪费了很多时间:(

终于介绍完啦!小伙伴们,这篇关于《不能在映射结构中调用外部结构》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>