Golang Notes

Structs do not have any empty value in Go.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
type dimension struct {
Height int
Width int
}

type Dog struct {
Breed string
WeightKg int
Size dimension `json:",omitempty"`
}

func main() {
d := Dog{
Breed: "pug",
}
b, _ := json.Marshal(d)
fmt.Println(string(b))
}
// prints:
// {"Breed":"pug","WeightKg":0,"Size":{"Height":0,"Width":0}}

In this case, even though we never set the value of the Size attribute, and set its omitempty tag,it still appears in the output. To solve this, use a struct pointer instead :

1
2
3
4
5
6
7
type Dog struct {
Breed string
WeightKg int
// Now `Size` is a pointer to a `dimension` instance
Size *dimension `json:",omitempty"`
}
// prints {"Breed":"pug","WeightKg":0}