Created
August 4, 2023 19:38
-
-
Save jdpedrie/2f68a917dcdfe7976198e42acc611f34 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ctypes | |
import "encoding/json" | |
type Nilable[T any] struct { | |
val *T | |
isSet bool | |
} | |
func NewNilable[T any](v T) Nilable[T] { | |
return Nilable[T]{ | |
val: &v, | |
isSet: true, | |
} | |
} | |
func (n *Nilable[T]) UnmarshalJSON(in []byte) error { | |
var v T | |
if err := json.Unmarshal(in, &v); err != nil { | |
return err | |
} | |
n.val = &v | |
n.isSet = true | |
return nil | |
} | |
func (n *Nilable[T]) MarshalJSON() ([]byte, error) { | |
if n.val == nil { | |
return nil, nil | |
} | |
return json.Marshal(n.val) | |
} | |
func (n *Nilable[T]) Get() *T { | |
return n.val | |
} | |
func (n *Nilable[T]) GetOrDefault() T { | |
if n.val == nil { | |
var v T | |
return v | |
} | |
return *n.val | |
} | |
func (n *Nilable[T]) Check() (*T, bool) { | |
return n.val, n.isSet | |
} | |
func (n *Nilable[T]) Set(v T) { | |
n.val = &v | |
n.isSet = true | |
} | |
func (n *Nilable[T]) Unset() { | |
n.val = nil | |
n.isSet = false | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment