Search code examples
jsonpointersgocomposite-literals

How to declare nullable json fields in golang structs?


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?


Solution

  • Add a helper function to your app:

    func NewString(s string) *string {
        return &s
    }
    

    And then you can use literals:

    // You can do this:
    book := &Book{
        Title: NewString("Book1"),
    }
    

    There are also libraries providing these NewXXX() functions so you don't have to add them (e.g. github.com/icza/gox/gox, disclosure: I'm the author).

    See related: How do I do a literal *int64 in Go?