2015-01-05 21:47
浏览 112

Golang levelDB结构

I'm trying to use following DB API: (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


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

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用以下数据库API: (基于简单文件的键/值DB)< / p>

我能够将“键”放入数据库中。 但是,我想知道value是否可以是诸如以下的结构: < pre> type Thm struct { 名称字符串 Age int }


   var Tmp Thm 
Tmp.Name =“ Gon” 
Tmp.Age = 33 
db.Put([] byte(“ test3”),[] byte(Tmp),nil)

现在,我收到的错误是“无法将Tmp(类型Thm)转换为[] byte。

使用levelDB的经验,您能帮我完成这些操作的正常情况吗? OR,我应该将struct转换为字节才能完成这项工作吗?


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duananyantan04633 2015-01-05 21:54

    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.

    打赏 评论

相关推荐 更多相似问题