英文:
Golang levelDB struct
问题
我正在尝试使用以下的DB API:https://godoc.org/github.com/syndtr/goleveldb/leveldb# (简单的基于文件的键值对数据库)
我已经能够将"key"放入数据库并获取它们。然而,我想知道值是否可以是一个结构体,例如:
type Thm struct {
Name string
Age int
}
然后,
var Tmp Thm
Tmp.Name = "Gon"
Tmp.Age = 33
db.Put([]byte("test3"), []byte(Tmp), nil)
目前,我得到的错误是"无法将Tmp(类型为Thm)转换为[]byte类型"。
如果你有使用levelDB的经验,你能帮我解决这个问题吗?
或者,我应该将结构体转换为字节以使其工作?
谢谢。
英文:
I'm trying to use following DB API: https://godoc.org/github.com/syndtr/goleveldb/leveldb#
(simple file based key/value DB)
I was able to put and get "key"s into the database.
However, I'm wondering if value can be a struct such as:
type Thm struct {
Name string
Age int
}
Then,
var Tmp Thm
Tmp.Name = "Gon"
Tmp.Age = 33
db.Put([]byte("test3"), []byte(Tmp), nil)
Right now, the error I'm getting is "cannot covert Tmp (type Thm) to type []byte.
If you have experiences with levelDB, could you help me how normally this will be done?
OR, should I convert struct into byte in order to make this work?
Thank you
答案1
得分: 0
levelDB
只支持字符串/字节数组作为键和值。这实际上是一个非常聪明的特性,因为它将复杂数据结构的序列化保留在应用程序级别。要序列化您的Thm
结构,您可以尝试使用gob包,如果您不需要其他语言的应用程序能够读取这些值,或者如果您需要将序列化数据访问其他语言,则可以使用protobufs、json或msgpack。
英文:
levelDB
only supports strings/byte arrays as keys and values. This is actually a pretty smart feature, because it keeps serialization of complex data structures at the application level. To serialize your Thm
struct you can try the gob package if you don't need applications in other languages to be able to read the values, or protobufs, json, or msgpack if you need the serialized data to be accessible to other languages.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论