Created
April 28, 2023 15:59
-
-
Save bagus2x/4bc49ecf8e87fdfb2f8bec0c966883ba to your computer and use it in GitHub Desktop.
Golang nullable with generic
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
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