Skip to content

Commit 8bbf023

Browse files
committed
add nullable type
Signed-off-by: Ashutosh Kumar <sonasingh46@gmail.com>
1 parent 53c0dbc commit 8bbf023

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

types/nullable.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package types
2+
3+
import "encoding/json"
4+
5+
type Nullable[T any] struct {
6+
Value T
7+
Set bool
8+
Null bool
9+
}
10+
11+
func (t *Nullable[T]) UnmarshalJSON(data []byte) error {
12+
t.Set = true
13+
return json.Unmarshal(data, &t.Value)
14+
}
15+
16+
func (t Nullable[T]) MarshalJSON() ([]byte, error) {
17+
return json.Marshal(t.Value)
18+
}
19+
20+
func (t *Nullable[T]) IsNullDefined() bool {
21+
return t.Set && t.Value == nil
22+
}
23+
24+
func (t *Nullable[T]) HasValue() bool {
25+
return t.Set && t.Value != nil
26+
}

types/nullable_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package types

0 commit comments

Comments
 (0)