Golang levelDB 结构体

huangapple go评论82阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2015年1月6日 05:47:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/27788453.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定