From 61e2f10196680e15f6d2e0f47e0ad06cc84a7611 Mon Sep 17 00:00:00 2001 From: Winni Neessen Date: Wed, 11 Sep 2024 11:23:33 +0200 Subject: [PATCH] Refactor Variable type and add omitted status Reorganized methods to ensure a logical method order and added the `present` field to track omitted values in JSON. This improves clarity and functionality by correctly indicating when a value was omitted. --- niljson.go | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/niljson.go b/niljson.go index 95312ea..a1bc839 100644 --- a/niljson.go +++ b/niljson.go @@ -10,13 +10,22 @@ import ( // Variable is a generic variable type that can be null. type Variable[T any] struct { - value T - notNil bool + value T + notNil bool + present bool } -// Value returns the value of the Variable -func (v *Variable[T]) Value() T { - return v.value +// IsNil returns true when a Variable is nil +func (v *Variable[T]) IsNil() bool { + return !v.notNil +} + +// NewVariable returns a new Variable of generic type +func NewVariable[T any](value T) Variable[T] { + return Variable[T]{ + notNil: true, + value: value, + } } // NotNil returns true when a Variable is not nil @@ -24,9 +33,9 @@ func (v *Variable[T]) NotNil() bool { return v.notNil } -// IsNil returns true when a Variable is nil -func (v *Variable[T]) IsNil() bool { - return !v.notNil +// Ommited returns true if a value was omitted in the JSON +func (v *Variable[T]) Ommited() bool { + return !v.present } // Reset resets the value to the Variable to a zero value and sets it to be nil @@ -36,12 +45,9 @@ func (v *Variable[T]) Reset() { v.notNil = false } -// NewVariable returns a new Variable of generic type -func NewVariable[T any](value T) Variable[T] { - return Variable[T]{ - notNil: true, - value: value, - } +// Value returns the value of the Variable +func (v *Variable[T]) Value() T { + return v.value } // NilBoolean is an boolean type that can be nil @@ -82,6 +88,7 @@ type NilString = Variable[string] // UnmarshalJSON satisfies the json.Unmarshaler interface for generic Variable types func (v *Variable[T]) UnmarshalJSON(data []byte) error { + v.present = true if string(data) != "null" { v.value = *new(T) v.notNil = true