12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package types
- import (
- "fmt"
- "encoding/json"
- )
- // The type represents the type safe nullable values
- // without pointers.
- type Nilable[V any] struct {
- value V
- valid bool
- }
- var _ = MustImplement[interface{
- fmt.Stringer
- json.Marshaler
- }](
- Nilable[Empty]{},
- )
- var _ = MustImplement[interface{
- json.Unmarshaler
- }](
- &Nilable[Empty]{},
- )
- func (n Nilable[V]) String() string {
- if !n.IsValid() {
- return "<nil>"
-
- }
- return fmt.Sprintf("%v", n.value)
- }
- func (n Nilable[V]) MarshalJSON() ([]byte, error) {
- if !n.valid {
- return []byte("null"), nil
- }
- return json.Marshal(n.value)
- }
- func (n *Nilable[V]) UnmarshalJSON(data []byte) error {
- if string(data) == "null" {
- var v [1]V
- n.valid = false
- n.value = v[0]
- return nil
- }
- err := json.Unmarshal(data, &n.value)
- if err != nil {
- return err
- }
- n.valid = true
- return nil
- }
- // Returns the the null of specified type.
- func Nil[V any]() Nilable[V] {
- return Nilable[V]{}
- }
- func Valid[V any](v V) Nilable[V] {
- return Nilable[V]{
- valid: true,
- value: v,
- }
- }
- // Returns the value and the validity of the value.
- func (n Nilable[V]) Got() (V, bool) {
- var buf [1]V
- if !n.valid {
- return buf[0], false
- }
- return n.value, n.valid
- }
- // Returns true if is not null.
- func (n Nilable[V]) IsValid() bool {
- return n.valid
- }
|