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个回答



问题在于类型转换(从 byte [] </ code>到 string </ code>等 。)。</ p>

您正在尝试打印 string </ code>值。 为避免不必要的转换,请进行以下修改:</ p>


  • data </ code>初始化更改为 data:= make(map [string] string) </ code> </ li>
  • 使用`data [string(Key)] = string(Value)将值分配到 data </ code>中(顺便说一下,不要对变量使用大写字母 您不打算导出)</ li>
  • 使用 fmt.Println(k +“:” + v))</ code>打印 data </ code>的值 </ li>
    </ ul>

    这应该产生以下结果:</ p>

      key0:value0 
    key1:value1
    key7:value7 \ nkey2:value2
    key3:value3
    key4:value4
    key5:value5
    key6:value6
    key8:value8
    key9:value9
    </ code> </ pre>
    </ div>

展开原文

原文

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

dongqiaogouk86049
dongqiaogouk86049 非常感谢您的回答,它确实有效。但是为什么价值会发生变化? 有点困惑。
大约 3 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐