Skip to content

Commit b7493ea

Browse files
authored
Add option.FromErr and option.Equal (#2186)
1 parent 141e9e6 commit b7493ea

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

pkg/option/option.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,15 @@ func FromPointer[T any](v *T) Option[T] {
7777
return Some[T](*v)
7878
}
7979

80+
// FromErr returns an Option[string] where a nil error is considered None
81+
// and any other value is considered Some, with the error message as the value.
82+
func FromErr(err error) Option[string] {
83+
if err == nil {
84+
return None[string]()
85+
}
86+
return Some(err.Error())
87+
}
88+
8089
// Some returns an Option with the given value and present set to true
8190
//
8291
// This means Some(nil) is a valid present Option

pkg/option/pkgfn.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,14 @@ func FoldLeft[T, R any](option Option[T], zero R, f func(accum R, value T) R) R
3939
}
4040
return zero
4141
}
42+
43+
// Equal returns true if both Options are equal.
44+
func Equal[T comparable](a, b Option[T]) bool {
45+
if a.present != b.present {
46+
return false
47+
}
48+
if !a.present {
49+
return true
50+
}
51+
return a.value == b.value
52+
}

0 commit comments

Comments
 (0)