From 168345c9e78dc7ebb97f2cb2f54b8a87b6beb49f Mon Sep 17 00:00:00 2001 From: Charles Iliya Krempeaux Date: Sun, 24 Sep 2023 09:40:03 +0900 Subject: [PATCH] initial commits --- nullable_marshaljson.go | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 nullable_marshaljson.go diff --git a/nullable_marshaljson.go b/nullable_marshaljson.go new file mode 100644 index 0000000..62cbacd --- /dev/null +++ b/nullable_marshaljson.go @@ -0,0 +1,29 @@ +package nul + +import ( + "fmt" + "encoding/json" +) + +var _ json.Marshaler = Nothing[bool]() +var _ json.Marshaler = Nothing[string]() + +// MarshalJSON makes it so json.Marshaler is implemented. +func (receiver Nullable[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) + } + + if receiver.isnull { + return json.Marshal(nil) + } + + return json.Marshal(receiver.value) +}