I usually like to use pointers for primitive data types in my structs so that when I json.Marshal them, the nil
fields are always translated to "field": null
in the json string. But this will make it difficult to create a new struct instance since I can't use literals.
For example:
type Book struct {
Price *float32 `json:"price"`
Title *string `json:"title"`
Author *string `json:"author"`
}
func main() {
// I can't do this
book := &Book{
Title: "Book1",
}
}
As you can see, when I use a string pointer, I can't initialise a struct easily unless I declare a variable for each pointer field and assign them to the struct fields. Is it possible to have both nullable json fields and the ease of initialising structs without declaring extra variables?