douguio0185 2017-07-25 11:53
浏览 90

golang leveldb获取快照错误

I am get leveldb's all key-val to a map[string][]byte, but it is not running as my expection. code is as below

package main
import (
    "fmt"
    "strconv"
    "github.com/syndtr/goleveldb/leveldb"
)
func main() {
    db, err := leveldb.OpenFile("db", nil)
    if err != nil {
        panic(err)
    }
    defer db.Close()
    for i := 0; i < 10; i++ {
        err := db.Put([]byte("key"+strconv.Itoa(i)), []byte("value"+strconv.Itoa(i)), nil)
        if err != nil {
            panic(err)
        }
    }
    snap, err := db.GetSnapshot()
    if err != nil {
        panic(err)
    }
    if snap == nil {
        panic("snap shot is nil")
    }
    data := make(map[string][]byte)
    iter := snap.NewIterator(nil, nil)
    for iter.Next() {
        Key := iter.Key()
        Value := iter.Value()
        data[string(Key)] = Value
    }
    iter.Release()
    if iter.Error() != nil {
        panic(iter.Error())
    }
    for k, v := range data {
        fmt.Println(string(k) + ":" + string(v))
    }
}

but the result is below key3:value9 key6:value9 key7:value9 key8:value9 key1:value9 key2:value9 key4:value9 key5:value9 key9:value9 key0:value9 rather not key0:value0

  • 写回答

1条回答 默认 最新

  • douluanzhao6689 2017-07-25 13:34
    关注

    Problem is with casting around types (byte[] to string, etc.).

    You are trying to print string values. To avoid unnecessary casting apply the following modifications:

    • Change data initialization into data := make(map[string]string)
    • Assign values into data with `data[string(Key)] = string(Value) (by the way, don't use capitalization for variables you aren't intend to export)
    • Print data's values with fmt.Println(k + ":" + v))

    This should produce the following result:

    key0:value0
    key1:value1
    key7:value7
    key2:value2
    key3:value3
    key4:value4
    key5:value5
    key6:value6
    key8:value8
    key9:value9
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统
  • ¥15 快手联盟怎么快速的跑出建立模型