opt.Optional[string].MarshalJSON()
parent
df716e8fe0
commit
a33304548a
10
optional.go
10
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.
|
||||
|
|
Loading…
Reference in New Issue