0

For example, there's this snippet in the dgo doc

// If omitempty is not set, then edges with empty values (0 for int/float, "" for string, false
// for bool) would be created for values not specified explicitly.

type Person struct {
    Uid      string     `json:"uid,omitempty"`
    Name     string     `json:"name,omitempty"`
    Age      int        `json:"age,omitempty"`
    Dob      *time.Time `json:"dob,omitempty"`
    Married  bool       `json:"married,omitempty"`
    Raw      []byte     `json:"raw_bytes,omitempty"`
    Friends  []Person   `json:"friend,omitempty"`
    Location loc        `json:"loc,omitempty"`
    School   []School   `json:"school,omitempty"`
    DType    []string   `json:"dgraph.type,omitempty"`
}

The comment is stated as if omitting omitempty is a bad thing.

sdfsdf
  • 5,052
  • 9
  • 42
  • 75

1 Answers1

0

As always, it depends... on your specific use-case and data model.

Having omitempty for a field results in that field missing in the json.Marshal result if its value is the types default zero value. Without omitempty the json will always include that field, and it will be the types default zero value if not set to something else. For example having following struct missing omitempty for the age field:

type Person struct {
   Uid      string     `json:"uid,omitempty"`
   Name     string     `json:"name,omitempty"`
   Age      int        `json:"age"
}

p := Person{
  Uid: "0x1",
}

js, _ := json.Marshal(&p)

The resulting json will have no name field, but age with the default zero value for an int, which is 0:

{"uid": "0x1", "age": 0}

If you send this json to a Dgraph mutation, age will be set to 0 for that node and overwrite the nodes current age value, while name will be unchanged. So in this case, having omitempty for the age fields makes sense, otherwise you would have to always set the age field to the correct value before calling a mutation with the json, even if you only want to change the name field of the node.

If you want a field to always be set to its default zero value if not set otherwise in the struct, then you don't use omitempty for that field.

xhad
  • 1
  • 1