-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstring_or.go
54 lines (47 loc) · 1005 Bytes
/
string_or.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package zhipu
import (
"bytes"
"encoding/json"
)
// StringOr is a struct that can be either a string or a value of type T.
type StringOr[T any] struct {
String *string
Value *T
}
var (
_ json.Marshaler = StringOr[float64]{}
_ json.Unmarshaler = &StringOr[float64]{}
)
// SetString sets the string value of the struct.
func (f *StringOr[T]) SetString(v string) {
f.String = &v
f.Value = nil
}
// SetValue sets the value of the struct.
func (f *StringOr[T]) SetValue(v T) {
f.String = nil
f.Value = &v
}
func (f StringOr[T]) MarshalJSON() ([]byte, error) {
if f.Value != nil {
return json.Marshal(f.Value)
}
return json.Marshal(f.String)
}
func (f *StringOr[T]) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
return nil
}
if bytes.Equal(data, []byte("null")) {
return nil
}
if data[0] == '"' {
f.String = new(string)
f.Value = nil
return json.Unmarshal(data, f.String)
} else {
f.Value = new(T)
f.String = nil
return json.Unmarshal(data, f.Value)
}
}