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
    
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面