tried to make type restriction a compile time constraint. that did not seem to work. so made it a run-time constraint.

master
Charles Iliya Krempeaux 2023-09-24 05:44:37 +09:00
parent 3f808e9749
commit 3cb587c984
1 changed files with 12 additions and 6 deletions

View File

@ -5,14 +5,20 @@ import (
"encoding/json" "encoding/json"
) )
type jsonMarshaler interface { var _ json.Marshaler = Nothing[bool]()
bool | string var _ json.Marshaler = Nothing[string]()
}
// MarshalJSON makes it so json.Marshaler is implemented. // MarshalJSON makes it so json.Marshaler is implemented.
func (receiver Optional[jsonMarshal]) MarshalJSON() ([]byte, error) { func (receiver Optional[T]) MarshalJSON() ([]byte, error) {
if !receiver.something { switch interface{}(receiver.value).(type) {
return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]()", receiver.value) case bool, string:
// these are OK.
default:
return nil, fmt.Errorf("cannot marshal something of type %T into JSON because parameterized type is %T rather than bool or string", receiver, receiver.value)
}
if receiver.isnothing() {
return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]() into JSON", receiver.value)
} }
return json.Marshal(receiver.value) return json.Marshal(receiver.value)