-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
120 lines (101 loc) · 2.35 KB
/
Copy pathexample_test.go
File metadata and controls
120 lines (101 loc) · 2.35 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package opt_test
import (
"encoding/json"
"fmt"
"github.com/coregx/opt"
)
func ExampleStringFrom() {
s := opt.StringFrom("hello")
data, _ := json.Marshal(s)
fmt.Println(string(data))
fmt.Println(s.Or("default"))
null := opt.NewString("", false)
data, _ = json.Marshal(null)
fmt.Println(string(data))
fmt.Println(null.Or("default"))
// Output:
// "hello"
// hello
// null
// default
}
func ExampleIntFrom() {
i := opt.IntFrom(42)
data, _ := json.Marshal(i)
fmt.Println(string(data))
fmt.Println(i.OrZero())
zero := opt.IntFrom(0)
fmt.Println(zero.IsZero()) // false — 0 is valid, not null
// Output:
// 42
// 42
// false
}
func ExampleField_patchAPI() {
type PatchUser struct {
Name opt.Field[string] `json:"name,omitzero"`
Email opt.Field[string] `json:"email,omitzero"`
Age opt.Field[int] `json:"age,omitzero"`
}
input := `{"name":"John","email":null}`
var patch PatchUser
json.Unmarshal([]byte(input), &patch)
fmt.Println("name absent:", patch.Name.IsAbsent())
fmt.Println("name value:", patch.Name.Or(""))
fmt.Println("email null:", patch.Email.IsNull())
fmt.Println("age absent:", patch.Age.IsAbsent())
// Output:
// name absent: false
// name value: John
// email null: true
// age absent: true
}
func ExampleMap() {
name := opt.From("John")
length := opt.Map(name, func(s string) int { return len(s) })
fmt.Println(length.OrZero())
null := opt.New("", false)
result := opt.Map(null, func(s string) int { return len(s) })
fmt.Println(result.IsZero())
// Output:
// 4
// true
}
func ExampleStringOrNull() {
valid := opt.StringOrNull("Moscow")
fmt.Println(valid.Or("unknown"))
null := opt.StringOrNull("")
fmt.Println(null.Or("unknown"))
fmt.Println(null.IsZero())
// Output:
// Moscow
// unknown
// true
}
func ExampleOrNull() {
i := opt.OrNull(42)
fmt.Println(i.OrZero()) // 42
z := opt.OrNull(0)
fmt.Println(z.IsZero()) // true — 0 means "not set"
s := opt.OrNull("hello")
fmt.Println(s.Or("default")) // hello
// Output:
// 42
// true
// hello
}
func ExampleOption_structJSON() {
type User struct {
Name opt.String `json:"name"`
Age opt.Int `json:"age"`
Score opt.Float `json:"score,omitzero"`
}
user := User{
Name: opt.StringFrom("Alice"),
Age: opt.NewInt(0, false),
}
data, _ := json.Marshal(user)
fmt.Println(string(data))
// Output:
// {"name":"Alice","age":null}
}