简体   繁体   中英

Go/Mgo -> []byte in MongoDB, slice of unaddressable array

I'm getting a:

reflect.Value.Slice: slice of unaddressable array

Error when I'm trying to add a sha256 hash to a mongoDB with mgo. Other []bytes work fine.

hash := sha256.Sum256(data)
err := c.Col.Insert(bson.M{"id": hash})

Any idea what the problem might be? I know I could encode the hash as a string but that should not be necessary.

That error means bson is treating hash as a []byte , but it is actually a [32]byte . The latter is an array value, and array values can't be sliced using the reflect package.

The fix is simple; give bson a slice of hash instead:

err := c.Col.Insert(bson.M{"id": hash[:]})

Ian Lance Taylor, one of the Go authors, explains this here: https://groups.google.com/d/msg/golang-nuts/ps0XdkIffQA/gekY8N0twBgJ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM