Skip to content

Commit

Permalink
Add ValueOrDefault to optional type (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
mokiat authored Mar 10, 2024
1 parent 746e473 commit dba7e48
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
9 changes: 9 additions & 0 deletions opt/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@ type T[D any] struct {
Value D
}

// ValueOrDefault returns the value held in this optional if it is specified,
// otherwise it returns the given fallback value.
func (t T[D]) ValueOrDefault(fallback D) D {
if t.Specified {
return t.Value
}
return fallback
}

// ToPtr returns a pointer-based representation of the value held
// in this optional. If this optional is not specified, then nil
// is returned.
Expand Down
7 changes: 7 additions & 0 deletions opt/value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ var _ = Describe("Optional", func() {
Expect(v.Value).To(Equal(actual))
})

It("is possible to get a fallback value", func() {
v := opt.Unspecified[string]()
Expect(v.ValueOrDefault("fallback")).To(Equal("fallback"))
v = opt.V("hello")
Expect(v.ValueOrDefault("fallback")).To(Equal("hello"))
})

It("is possible to get a pointer representation of an unspecified value", func() {
v := opt.Unspecified[string]()
ptr := v.ToPtr()
Expand Down

0 comments on commit dba7e48

Please sign in to comment.