File tree Expand file tree Collapse file tree 2 files changed +102
-0
lines changed Expand file tree Collapse file tree 2 files changed +102
-0
lines changed Original file line number Diff line number Diff line change
1
+ package utils
2
+
3
+ type Options [T any ] struct {
4
+ values T
5
+ none bool
6
+ }
7
+
8
+ type OptionInterface [T any ] interface {
9
+ IsSome () bool
10
+ IsNone () bool
11
+ Unwrap () T
12
+ Expect (msg string ) T
13
+ UnwrapOr (defaultValue T ) T
14
+ IsSomeAnd (fn func (args ... interface {}) bool ) bool
15
+ Inspect () Options [T ]
16
+ }
17
+
18
+ func Some [T any ](value T ) Options [T ] {
19
+ return Options [T ]{values : value , none : false }
20
+ }
21
+
22
+ func None [T any ]() Options [T ] {
23
+ return Options [T ]{none : true }
24
+ }
25
+
26
+ func (o Options [T ]) IsSome () bool {
27
+ return ! o .none
28
+ }
29
+
30
+ func (o Options [T ]) IsNone () bool {
31
+ return o .none
32
+ }
33
+
34
+ func (o Options [T ]) Unwrap () T {
35
+ if o .none {
36
+ panic ("Unwrap: Option is None" )
37
+ }
38
+ return o .values
39
+ }
40
+
41
+ func (o Options [T ]) Expect (msg string ) T {
42
+ if o .none {
43
+ panic ("Expect: " + msg )
44
+ }
45
+ return o .values
46
+ }
47
+
48
+ func (o Options [T ]) UnwrapOr (defaultValue T ) T {
49
+ if o .none {
50
+ return defaultValue
51
+ }
52
+ return o .values
53
+ }
54
+
55
+ func (o Options [T ]) IsSomeAnd (fn func (args ... interface {}) bool ) bool {
56
+ if o .none {
57
+ return false
58
+ }
59
+ return fn (o .values )
60
+ }
61
+
62
+ func (o Options [T ]) Inspect () Options [T ] {
63
+ return o
64
+ }
65
+
66
+ func Option [T any ](value T ) Options [T ] {
67
+ if (& value == nil ){
68
+ return None [T ]()
69
+ }else {
70
+ return Some [T ](value )
71
+ }
72
+ }
73
+ type People struct {
74
+ Age int
75
+ Name string
76
+ Address string
77
+ }
78
+
79
+ func main (){
80
+ var age * int = nil ;
81
+ ok := Option (age )
82
+ vals := * ok .Expect ("this is nil pointer" )
83
+ somePeople := Option (& People {
84
+ Age : 20 ,
85
+ Name : "Gog" ,
86
+ Address : "Mars" ,
87
+ })
88
+ somePeople .Unwrap ()
89
+ }
Original file line number Diff line number Diff line change @@ -184,3 +184,16 @@ func TimeDuration(duration string) (time.Time, error) {
184
184
}
185
185
return time .Now ().Add (time .Duration (durationSecond ) * time .Second ).UTC (), nil
186
186
}
187
+
188
+ func Chunk (slice []int , size int ) [][]int {
189
+ var chunks [][]int
190
+ for i := 0 ; i < len (slice ); i += size {
191
+ end := i + size
192
+ if end > len (slice ) {
193
+ end = len (slice )
194
+ }
195
+ chunks = append (chunks , slice [i :end ])
196
+ }
197
+ return chunks
198
+ }
199
+
You can’t perform that action at this time.
0 commit comments