diff --git a/optional.go b/optional.go index e46dafc..530d16e 100644 --- a/optional.go +++ b/optional.go @@ -2,6 +2,7 @@ package opt import ( "fmt" + "encoding/json" ) // Optional represents an optional value. @@ -169,6 +170,15 @@ func (receiver Optional[T]) GoString() string { return fmt.Sprintf("opt.Something[%T](%#v)", receiver.value, receiver.value) } +// MarshalJSON makes it so json.Marshaler is implemented. +func (receiver Optional[string]) MarshalJSON() ([]byte, error) { + if !receiver.something { + return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]()", receiver.value) + } + + return json.Marshal(receiver.value) +} + // WhenNothing will call ‘fn’ when ‘receiver’ is holding nothing. // // It will not call ‘fn’ when ‘receier’ is hold something.