我有一个双链表:
type node[T any] struct {
info T
next *node[T]
prev *node[T]
}
type List[T any] struct {
head *node[T]
tail *node[T]
size int
}
我想要方法func (list List[T]) ToByte() (error, []byte)
,它将返回这个列表中任何数据的字节。我已经尝试了一些方法,例如,使用binary.Write()
,但它不能处理任何数据(例如,它不能处理字符串)。
在我看来,这是可能的,因为任何数据都以字节的形式存储在内存中,我所需要做的就是简单地从内存中取出所有字节。
你可以使用encoding/gob
,它与Go类型工作得更好,比说encoding/json
或encoding/xml
更有效,但它仍然不能编码函数和通道类型和递归值(但递归类型工作得很好),所以你不能真正使用any
作为约束
以下是ToByte
使用encoding/gob
的示例:https://go.dev/play/p/A5hCXCCThm6