go - golang leveldb get snapshot error -
i leveldb's key-val map[string][]byte, not running expection. code 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() := 0; < 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 nil") } data := make(map[string][]byte) iter := snap.newiterator(nil, nil) iter.next() { key := iter.key() value := iter.value() data[string(key)] = value } iter.release() if iter.error() != nil { panic(iter.error()) } k, v := range data { fmt.println(string(k) + ":" + string(v)) } }
but result 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
problem casting around types (byte[]
string
, etc.).
you trying print string
values. avoid unnecessary casting apply following modifications:
- change
data
initializationdata := make(map[string]string)
- assign values
data
`data[string(key)] = string(value) (by way, don't use capitalization variables aren't intend export) - print
data
's valuesfmt.println(k + ":" + v))
this should produce following result:
key0:value0 key1:value1 key7:value7 key2:value2 key3:value3 key4:value4 key5:value5 key6:value6 key8:value8 key9:value9
Comments
Post a Comment