Skip to content

Instantly share code, notes, and snippets.

@jdpedrie
Created August 4, 2023 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdpedrie/2f68a917dcdfe7976198e42acc611f34 to your computer and use it in GitHub Desktop.
Save jdpedrie/2f68a917dcdfe7976198e42acc611f34 to your computer and use it in GitHub Desktop.
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