There are two structures A & B. B includes A. Also there is a function attached to A. It returns json of the parent object. I expect to see all object fields in json when I call the fonction on instance of B, but I get only fields of A. Please look at the code:
type A struct {
Foo string
}
type B struct {
A
Bar string
}
func (object *A) toJson() []byte {
res, _ := json.Marshal(&object)
return res
}
func main() {
b := B{}
fmt.Println(string(b.toJson()))
}
I expect to get {"Foo":"", "Bar":""} but the result is {"Foo":""}. The first way is to define two separate functions for both of structures. But is there the second solution with one function? Thank you in advance.
Your methodn toJson() is from A struct. change it to struct B then you will get your expected result.
package main
import (
"encoding/json"
"fmt"
)
type A struct {
Foo string `json:"foo"`
}
type B struct {
A
Bar string `json:"bar"`
}
func (object *B) toJson() []byte {
res, _ := json.Marshal(&object)
return res
}
func main() {
c := B{}
fmt.Println(string(c.toJson()))
}
Since toJson
is defined for A
, it operates on b.A
. Embedding a type in Go is not the same as subclassing in other languages. See https://golang.org/doc/effective_go.html#embedding.