解组嵌套结构和类型断言
来源:stackoverflow
时间:2024-04-10 12:57:35 111浏览 收藏
golang学习网今天将给大家带来《解组嵌套结构和类型断言》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习Golang或者已经是大佬级别了,都非常欢迎也希望大家都能给我建议评论哈~希望能帮助到大家!
我想在 go 中编组和解组类似二叉树的结构。每个节点对应一个 node 类型的结构体。节点通过指针(左子节点和右子节点)互连,就像链表一样。树叶承载着作为接口实现的内容。树的所有叶子都具有相同类型的内容,解组器事先知道该内容类型。
我知道,当在一个字段(例如“内容”)中使用接口解组结构时,我必须执行类似的类型断言
err = json.unmarshal(byteslice, &decodedstruct{content: &mystruct{}})
然而,由于树的大小是任意的,我的结构是深度嵌套的。 是否有一种简单/惯用的方式来编组/解组这样一个我不知道的对象?
下面,我发布了一个最小的示例,我认为它代表了两个关键特征:第一,指针序列,第二,“末尾”的接口。 (演示:https://play.golang.org/p/t9c9hn4onle)
// LinkedList is a simple linked list defined by a root node type LinkedList struct { Name string Root *Node } // Node is a list's node with Content type Node struct { Child *Node C Content } // Content is a dummy interface type Content interface { CalculateSum() int } // MyStruct implements Content type MyStruct struct { ID int Values []int } // CalculateSum computes the sum of the slice in the field @Values func (ms MyStruct) CalculateSum() (s int) { for _, i := range ms.Values { s += i } return } func main() { // Make a list of three nodes with content in the leaf ms := MyStruct{2, []int{2, 4, 7}} leaf := Node{nil, ms} node := Node{&leaf, nil} rootNode := Node{&node, nil} ll := LinkedList{"list1", &rootNode} // Encoding linked list works fine... llEncoded, err := json.Marshal(ll) // ...decoding doesn't: // error decoding: json: cannot unmarshal object into Go struct field Node.Root.Child.Child.C of type main.Content llDecoded := LinkedList{} err = json.Unmarshal(llEncoded, &llDecoded) fmt.Println("error decoding: ", err) }
解决方案
如果您预先知道 content
的具体类型,则可以实现 json.unmarshaler
接口,解组为硬编码的具体类型,然后将结果分配给接口类型。
func (n *node) unmarshaljson(data []byte) error { var node struct { child *node c *mystruct } if err := json.unmarshal(data, &node); err != nil { return err } n.child = node.child n.c = node.c return nil }
https://play.golang.org/p/QOJuiLpYrze
如果您需要它更加灵活,您需要以某种方式告诉 json.unmarshaler
实现 json 代表什么具体类型。例如,您可以执行此操作的一种方法是将类型信息嵌入到内容的 json 中(现在借助 json.marshaler
接口):
func (ms mystruct) marshaljson() ([]byte, error) { type _mystruct mystruct var out = struct { type string `json:"_type"` _mystruct }{ type: "mystruct", _mystruct: _mystruct(ms), } return json.marshal(out) }
相应地更新 node
的解组器实现:
func (n *node) unmarshaljson(data []byte) error { var node struct { child *node c json.rawmessage } if err := json.unmarshal(data, &node); err != nil { return err } n.child = node.child if len(node.c) > 0 && string(node.c) != `null` { var _type struct { type string `json:"_type"` } if err := json.unmarshal([]byte(node.c), &_type); err != nil { return err } c := newcontent[_type.type]() if err := json.unmarshal([]byte(node.c), c); err != nil { return err } n.c = c } return nil }
并将 newcontent
定义为一个映射,其值是返回具体类型的新实例的函数:
var newContent = map[string]func() Content{ "MyStruct": func() Content { return new(MyStruct) }, // ... }
尝试一下演示:https://play.golang.org/p/u9L0VxEG4dT
今天关于《解组嵌套结构和类型断言》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习