msgpack in go: Use an already existing struct (that we cannot modify) in a library and add a "type" field with the name of the struct. The struct does have multiple subtypes that all implement the same interface (Node) and can also have children of that interface. Then deserialize that data in rust in an enum
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Since you can't modify the structs, you need to wrap them in a custom struct that adds the "type" field.
Step 1: Define a wrapper struct
go
type NodeWrapper struct {
Type string `msgpack:"type"`
Value *string `msgpack:"value,omitempty"` // only for TextNode
Children []NodeWrapper `msgpack:"children"`
}
Step 2: Convert from Node to NodeWrapper
go
func wrapNode(n Node) NodeWrapper {
switch v := n.(type) {
case *TextNode:
return NodeWrapper{
Type: "TextNode",
Value: &v.Value,
Children: wrapNodes(v.Children),
}
case *DivNode:
return NodeWrapper{
Type: "DivNode",
Children: wrapNodes(v.Children),
}
default:
panic("unknown node type")
}
}
func wrapNodes(nodes []Node) []NodeWrapper {
var out []NodeWrapper
for _, n := range nodes {
out = append(out, wrapNode(n))
}
return out
}