Search code examples
mongodbgomgo

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.


Solution

  • 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