I would love to understands why the following sample code for passing both books and &books yields the result of the custom MarshalJSON() method defined on the pointer receiver *Book. I do understand that the method set of Book does not include the custom MarshalJSON() method.
package main
import (
"encoding/json"
"fmt"
)
func main() {
book := Book{
Author: Author{
FirstName: "Astrid",
LastName: "Lindgren",
},
}
books := []Book{}
books = append(books, book)
a, _ := json.Marshal(book)
fmt.Println(string(a)) // {"author":{"first_name":"Astrid","last_name":"Lindgren"}}
b, _ := json.Marshal(&book)
fmt.Println(string(b)) // {"author":"Astrid Lindgren"}
c, _ := json.Marshal(books)
fmt.Println(string(c)) // [{"author":"Astrid Lindgren"}]
d, _ := json.Marshal(&books)
fmt.Println(string(d)) // [{"author":"Astrid Lindgren"}]
}
type Book struct {
Author Author `json:"author"`
}
type Author struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
type BookJSON struct {
Author string `json:"author"`
}
func (r *Book) ToJSONModel() BookJSON {
return BookJSON{
Author: r.Author.FirstName + " " + r.Author.LastName,
}
}
func (r *Book) MarshalJSON() ([]byte, error) {
return json.Marshal(r.ToJSONModel())
}
Here is a link to go playground: https://goplay.tools/snippet/x3vZCUnHcsL
Is it because the values inside the slice books are addressable whereas the single value book is not?