DEV Community

Discussion on: How to Handle Missing Fields From A Struct in Go?

Collapse
 
rafaacioly profile image
Rafael Acioly

Nice trick Mohammad I didn't know that if we use pointers on types we get nil values, but be careful with this because you can have panic errors if you forgot to check if it's a nil or int, what I would do is keep the type as it is and add a method to check if the field is not zero, like this:

type Building struct {
    WindowCount int `json:"window_count"`
    Doors       int `json:"doors"`
}

func (b Building) HasDoors() bool {
    return b.Doors > 0
}
Enter fullscreen mode Exit fullscreen mode

This way I don't need to check if the field is nil and can still perform arithmetic operations.

var b = Building{WindowCount: 1}
b.Doors += 1
Enter fullscreen mode Exit fullscreen mode