When marshaling a struct with an inline struct that has custom BSON marshaling, some of the fields in the "parent" struct don't get marshaled.
Here is the minimal code to reproduce the problem:
package main
import (
"fmt"
"log"
"reflect"
"gopkg.in/mgo.v2/bson"
)
type Person struct {
Name string
}
func (p *Person) GetBSON() (interface{}, error) {
return struct {
Name string
}{
Name: p.Name,
}, nil
}
type Student struct {
Person `bson:",inline"`
Course string
}
func main() {
s := &Student{
Person: Person{Name: "Alberto"},
Course: "math",
}
bytes, err := bson.Marshal(s)
if err != nil {
log.Fatal("marshaling: ", err)
}
ss := &Student{}
if err := bson.Unmarshal(bytes, ss); err != nil {
log.Fatal("unmarshaling: ", err)
}
if !reflect.DeepEqual(s, ss) {
fmt.Println("ERROR: students differ!")
fmt.Println(s)
fmt.Println(ss)
} else {
fmt.Println("OK: students are the same!")
}
}
The code above compares and student before and after marshal/unmarshal. The student after the marshaling is missing the specific fields of the Student struct (i.e. "courses") and only has the fields in the inlined struct ("Person.Name").
If I comment out the "Person.GetBSON" method, the code works just fine, and the student is equal before and after the marshal/unmarshal.
Wha I'm doing wrong?