How can I use a codec for 'kind' for setting the NilAsEmpty SliceCodec?

I’m attempting to use bsonoptions.SliceCodec().SetEncodeNilAsEmpty(true), but I’m having issues building the registry. This is what I have so far:

registry := bsoncodec.NewRegistryBuilder()
bsoncodec.DefaultValueEncoders{}.RegisterDefaultEncoders(registry)
nilSliceCodec := bsoncodec.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(true))
registry.RegisterDefaultEncoder(reflect.Slice, nilSliceCodec)
opts.SetRegistry(registry.Build())

When I do not override the registry, my tests work fine. When I add this hunk of code though, I start getting back this error: no decoder found for interface {}.
My current guess is that RegisterDefaultEncoders isn’t registering the proper encoder for interfaces, but I’m a little unclear about how to specify them.

@Isabella_Siu - any ideas on what I might be doing wrong here?

Hi @TopherGopher,

With this code, you’re only registering encoders, and instead, you likely want to do the followng:

nilSliceCodec := bsoncodec.NewSliceCodec(bsonoptions.SliceCodec().SetEncodeNilAsEmpty(true))
registry := bson.NewRegistryBuilder().RegisterTypeEncoder(reflect.Slice, nilSliceCodec).Build()

The difference is that bson.NewRegistryBuilder pre-registers all the default encoders and decoders (which can then be overwritten) while bsoncodec.NewRegistryBuilder sets up an empty registry builder.

1 Like