A way to handle nil values.
Use Go 1.18+ is a must. Goption uses Generics.
This is a copy of Java Optional. It contains almost all functions
- Empty
- Of
- Optional.Get
- Optional.IsPresent
- Optional.OrElseError
- Optional.OrElse
- Optional.GetValue
And others made specifically to go:
- Optional.MustGet
You can use goption.Optional to sql package. Optional implements sql.Scanner and sql.Valuer
Unfortunately ,omitempty
is not supported by now due how json.Marshal works. For more details can see this link.
edit: Now in Go version 1.24 IsZero() function is called by encoding/json when ,omitzero
tag is set.
There is a special use for boolean type. By default, true and false will be valid when are unmarshal from json or text. The only option to handle as invalid bool (nil) is assigning it as a pointer:
type User struct {
IsValid goption.Optional[*bool] // if false will be invalid
}
type Client struct {
IsValid goption.Optional[bool] // if false will be valid
}
These values are taken as true:
- true
- 1
- on
- yes
And these other as false:
- false
- 0
- off
- no
This is the design decision I had to make. If any please create an issue if you have a better idea for this :D