Hey @MoongooDB, thanks for the question! I believe that behavior is intentional and is partially a limitation of the BSON format specification, which requires all document keys to be strings (Go map types are encoded as nested documents). The Go BSON marshaler doesn’t define a standard way to convert a [2]byte to a string, so the Marshal call fails. However, you can define that conversion yourself by making your map key type implement the bsoncodec.KeyMarshaler interface:
type KeyMarshaler interface {
MarshalKey() (key string, err error)
}
Here’s an example starting with your code sample (check out a working version here):
package main
import (
"encoding/hex"
"fmt"
"go.mongodb.org/mongo-driver/bson"
)
type myByteMapKey [2]byte
func (key myByteMapKey) MarshalKey() (string, error) {
return hex.EncodeToString(key[:]), nil
}
type myByteMap map[myByteMapKey]string
func main() {
data := myByteMap{
myByteMapKey{0, 0}: "Hello",
}
binData, err := bson.Marshal(data)
if err != nil {
panic(err)
}
fmt.Println(binData)
}
To unmarshal the output, you’d then have to implement the bsoncodec.KeyUnmarshaler interface for the myByteMapKey type.
@xunjie_liu that’s expected behavior. Your example with the *myByteMapKey receiver for MarshalKey() doesn’t work because the encoded key type and the method receiver type must match exactly. The pointer check in the code you linked only disallows nil pointers.