option.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package generics
  2. type Option[V any] struct {
  3. // Value must be zeroed when Ok is false for deterministic comparability.
  4. Value V
  5. // bool is the smallest type, so putting it at the end increases the chance it can be packed
  6. // with Value.
  7. Ok bool
  8. }
  9. func (me Option[V]) UnwrapOrZeroValue() (_ V) {
  10. if me.Ok {
  11. return me.Value
  12. }
  13. return
  14. }
  15. func (me *Option[V]) UnwrapPtr() *V {
  16. if !me.Ok {
  17. panic("not set")
  18. }
  19. return &me.Value
  20. }
  21. func (me Option[V]) Unwrap() V {
  22. if !me.Ok {
  23. panic("not set")
  24. }
  25. return me.Value
  26. }
  27. // Deprecated: Use option.AndThen
  28. func (me Option[V]) AndThen(f func(V) Option[V]) Option[V] {
  29. if me.Ok {
  30. return f(me.Value)
  31. }
  32. return me
  33. }
  34. func (me Option[V]) UnwrapOr(or V) V {
  35. if me.Ok {
  36. return me.Value
  37. } else {
  38. return or
  39. }
  40. }
  41. func (me *Option[V]) Set(v V) (prev Option[V]) {
  42. prev = *me
  43. me.Ok = true
  44. me.Value = v
  45. return
  46. }
  47. func (me *Option[V]) SetNone() {
  48. me.Ok = false
  49. me.Value = ZeroValue[V]()
  50. }
  51. func (me *Option[V]) SetFromTuple(v V, ok bool) {
  52. *me = OptionFromTuple(v, ok)
  53. }
  54. func (me *Option[V]) SetSomeZeroValue() {
  55. me.Ok = true
  56. me.Value = ZeroValue[V]()
  57. }
  58. func Some[V any](value V) Option[V] {
  59. return Option[V]{Ok: true, Value: value}
  60. }
  61. func None[V any]() Option[V] {
  62. return Option[V]{}
  63. }
  64. func OptionFromTuple[T any](t T, ok bool) Option[T] {
  65. if ok {
  66. return Some(t)
  67. } else {
  68. return None[T]()
  69. }
  70. }