opt.Optional[string].MarshalJSON()
parent
df716e8fe0
commit
a33304548a
10
optional.go
10
optional.go
|
@ -2,6 +2,7 @@ package opt
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"encoding/json"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Optional represents an optional value.
|
// 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)
|
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.
|
// WhenNothing will call ‘fn’ when ‘receiver’ is holding nothing.
|
||||||
//
|
//
|
||||||
// It will not call ‘fn’ when ‘receier’ is hold something.
|
// It will not call ‘fn’ when ‘receier’ is hold something.
|
||||||
|
|
Loading…
Reference in New Issue