pointers - 解码嵌套结构和类型断言

标签 pointers go interface linked-list unmarshalling

我想在 Go 中编码和解码类似二叉树的结构。每个节点对应一个 Node 类型的结构。节点通过指针(左右子节点)相互连接,就像在链表中一样。树的叶子承载着作为接口(interface)实现的内容。一棵树的所有叶子都具有相同类型的内容,这是解码器事先知道的。
我知道当在一个字段中解码具有接口(interface)的结构时(比如“内容”),我必须做一个类型断言,比如err = json.Unmarshal(byteSlice, &decodedStruct{Content: &MyStruct{}})然而,由于树的大小是任意的,我的结构是深度嵌套的。
是否有一种直接/惯用的方式来编码/解码这样一个我不知道的对象?
下面,我发布了一个最小的示例,我认为它代表了两个关键特性,第一个是指针序列,第二个是“末端”的接口(interface)。
(游乐场: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接口(interface),解码为硬编码的具体类型,然后将结果分配给接口(interface)类型。

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 接口(interface)):
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

关于pointers - 解码嵌套结构和类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62816564/

相关文章:

go - 在 IntelliJ 中导入 Go 项目不起作用

slice 接口(interface)上的 Golang Switch Case

java - 在泛型类中扩展 Interface 时出现 NoSuchFieldError

C# public 仅适用于相同接口(interface)的类

go - Logger.Writer.(*os.File) (左侧的非接口(interface)类型 func() io.Writer)

c++ - 你能改变指针指向的大小吗

c - 在函数中传递指针的重要性是什么?

C 程序 - 指针数组乘法

c - 如何从我的自定义队列中取出元素

go - Base64 编码不会因无效字符而失败