summaryrefslogtreecommitdiff
path: root/common
diff options
context:
space:
mode:
authorKeuin <[email protected]>2022-09-08 00:31:26 +0800
committerKeuin <[email protected]>2022-09-08 00:31:26 +0800
commita720c2c16b442b668db465fbbc70740cfc7ddee4 (patch)
treeaac1ba37e4a19c3e9c34f70e9297b0a9e3803db6 /common
parentd00c97e9dbfb59672ced042af8a6e849efab98cc (diff)
Load config from file or cli.
Diffstat (limited to 'common')
-rw-r--r--common/orelse.go49
1 files changed, 45 insertions, 4 deletions
diff --git a/common/orelse.go b/common/orelse.go
index a96bde7..29e3dc7 100644
--- a/common/orelse.go
+++ b/common/orelse.go
@@ -1,20 +1,61 @@
package common
-type Opt[T any] struct {
+import "reflect"
+
+type Opt[T any] interface {
+ OrElse(thing T) T
+}
+
+type OptError[T any] struct {
thing T
err error
}
-func Optional[T any](thing T, err error) Opt[T] {
- return Opt[T]{
+type OptNull[T any] struct {
+ ptr *T
+}
+
+type OptZero[T any] struct {
+ thing T
+}
+
+func (o OptNull[T]) OrElse(thing T) T {
+ if o.ptr != nil {
+ return *o.ptr
+ }
+ return thing
+}
+
+func Errorable[T any](thing T, err error) Opt[T] {
+ return OptError[T]{
thing: thing,
err: err,
}
}
-func (o Opt[T]) OrElse(thing T) T {
+func (o OptError[T]) OrElse(thing T) T {
if o.err != nil {
return thing
}
return o.thing
}
+
+func Nullable[T any](ptr *T) Opt[T] {
+ return OptNull[T]{
+ ptr: ptr,
+ }
+}
+
+func Zeroable[T any](thing T) Opt[T] {
+ return OptZero[T]{
+ thing: thing,
+ }
+}
+
+func (o OptZero[T]) OrElse(thing T) T {
+ var zero T
+ if reflect.DeepEqual(zero, o.thing) {
+ return thing
+ }
+ return o.thing
+}