Skip to content

Instantly share code, notes, and snippets.

@bagus2x
Created April 28, 2023 15:59
Show Gist options
  • Save bagus2x/4bc49ecf8e87fdfb2f8bec0c966883ba to your computer and use it in GitHub Desktop.
Save bagus2x/4bc49ecf8e87fdfb2f8bec0c966883ba to your computer and use it in GitHub Desktop.
Golang nullable with generic
type Null[T any] struct {
Value T
Valid bool
Set bool
}
func (n *Null[T]) UnmarshalJSON(data []byte) error {
n.Set = true
if string(data) == "null" {
n.Valid = false
return nil
}
var temp T
if err := json.Unmarshal(data, &temp); err != nil {
return err
}
n.Value = temp
n.Valid = true
return nil
}
func (n Null[T]) MarshalJSON() ([]byte, error) {
if n.Set {
if n.Valid {
return json.Marshal(n.Value)
} else {
return []byte("null"), nil
}
}
return nil, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment