Install: go get -u github.com/ifnotnil/opt
Golang generic optional type with support for json.Marshaler, json.Unmarshaler, driver.Valuer, sql.Scanner and golang 1.24 json omitzero tag.
The main ideas are:
- Separate present-but-nil from not present (e.g., for the HTTP PATCH method).
- Implement optional values without using pointers.
| State | Constructor function | Description |
|---|---|---|
| None | None[T]() |
Value is absent, not preset nor nil. |
| Nil | Nil[T]() |
Value is present but nil |
| Valid | New[T](t T) |
Value is preset and valid (not nil) |
Given a struct
type Foo struct {
A Optional[int] `json:"a"`
}| Json | Resulted state of A |
|---|---|
{} |
None |
{"a": null} |
Nil |
{"a": 123} |
Valid |
We can achieve that by writing the optional value using one of the constructor functions.
a := Nil["string")
// ...
a = New("test")