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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办