From 3cb587c98420965c31eb4f1ef4cadf6482681c18 Mon Sep 17 00:00:00 2001 From: Charles Iliya Krempeaux Date: Sun, 24 Sep 2023 05:44:37 +0900 Subject: [PATCH] tried to make type restriction a compile time constraint. that did not seem to work. so made it a run-time constraint. --- optional_marshaljson.go | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/optional_marshaljson.go b/optional_marshaljson.go index 6233092..4d144cb 100644 --- a/optional_marshaljson.go +++ b/optional_marshaljson.go @@ -5,14 +5,20 @@ import ( "encoding/json" ) -type jsonMarshaler interface { - bool | string -} +var _ json.Marshaler = Nothing[bool]() +var _ json.Marshaler = Nothing[string]() // MarshalJSON makes it so json.Marshaler is implemented. -func (receiver Optional[jsonMarshal]) MarshalJSON() ([]byte, error) { - if !receiver.something { - return nil, fmt.Errorf("cannot marshal opt.Nothing[%T]()", receiver.value) +func (receiver Optional[T]) MarshalJSON() ([]byte, error) { + switch interface{}(receiver.value).(type) { + 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)