nil.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package types
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. // The type represents the type safe nullable values
  7. // without pointers.
  8. type Nilable[V any] struct {
  9. value V
  10. valid bool
  11. }
  12. var _ = MustImplement[interface{
  13. fmt.Stringer
  14. json.Marshaler
  15. }](
  16. Nilable[Empty]{},
  17. )
  18. var _ = MustImplement[interface{
  19. json.Unmarshaler
  20. }](
  21. &Nilable[Empty]{},
  22. )
  23. func (n Nilable[V]) String() string {
  24. if !n.IsValid() {
  25. return "<nil>"
  26. }
  27. return fmt.Sprintf("%v", n.value)
  28. }
  29. func (n Nilable[V]) MarshalJSON() ([]byte, error) {
  30. if !n.valid {
  31. return []byte("null"), nil
  32. }
  33. return json.Marshal(n.value)
  34. }
  35. func (n *Nilable[V]) UnmarshalJSON(data []byte) error {
  36. if string(data) == "null" {
  37. var v [1]V
  38. n.valid = false
  39. n.value = v[0]
  40. return nil
  41. }
  42. err := json.Unmarshal(data, &n.value)
  43. if err != nil {
  44. return err
  45. }
  46. n.valid = true
  47. return nil
  48. }
  49. // Returns the the null of specified type.
  50. func Nil[V any]() Nilable[V] {
  51. return Nilable[V]{}
  52. }
  53. func Valid[V any](v V) Nilable[V] {
  54. return Nilable[V]{
  55. valid: true,
  56. value: v,
  57. }
  58. }
  59. // Returns the value and the validity of the value.
  60. func (n Nilable[V]) Got() (V, bool) {
  61. var buf [1]V
  62. if !n.valid {
  63. return buf[0], false
  64. }
  65. return n.value, n.valid
  66. }
  67. // Returns true if is not null.
  68. func (n Nilable[V]) IsValid() bool {
  69. return n.valid
  70. }