opt.Optional[string].MarshalJSON()

master
Charles Iliya Krempeaux 2023-09-23 07:36:42 +09:00
parent df716e8fe0
commit a33304548a
1 changed files with 10 additions and 0 deletions

View File

@ -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.