-
Type: Bug
-
Resolution: Duplicate
-
Priority: Unknown
-
None
-
Affects Version/s: None
-
Component/s: None
From a forum post:
Hi there,
I am trying to work with an interface{}
I have an object of type foo containing an interface ActivationInterface ; this object is persisted and I have trouble fetching it back, as the underlying type of the inner object is not known.
I implemented UnmarshalBSON as follow without success ; it seems that even after setting the concrete type of the interface, the unmarshaler still does now the underlying type and I still get the error: error decoding key act: no decoder found for main.ActivationInterface
I tried replacing everything BSON related by JSON ; and it works.
Here are both examples:
Erroring UnmarshalBSON: Go Playground - The Go Programming Language
Almost the same code, but woking using UnmarshallJSON: Go Playground - The Go Programming LanguageDo you have any idea on what is happening ?
Thanks !
tldr; Unmarshaling JSON into an instance of a struct with an empty interface field that has a value assigned to it unmarshals into the assigned value correctly. The BSON unmarshaler ignores the assigned value and only considers the field type in the struct definition, resulting into an unmarshal error.
E.g.
type foo struct { Val interface{} } a := foo{Val: ""} b := foo{Val: 0} // a and b should unmarshal using the type of the value assigned to Val, not interface{}
See StructCodec.describeStruct, which takes a reflect.Type instead of a reflect.Value, meaning it can't access the original value that might have additional type information. Additionally, the struct description caching (see here) complicates getting different values for the fields of the same struct type.
- duplicates
-
GODRIVER-1808 Unmarshaling BSON into a struct with interface fields containing concrete value types doesn't work as expected.
- Closed