Skip to content

Commit

Permalink
Support Stringer interface on Optional[T]
Browse files Browse the repository at this point in the history
Signed-off-by: moznion <moznion@mail.moznion.net>
  • Loading branch information
moznion committed Nov 16, 2022
1 parent 1ee700f commit e1e26cc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
13 changes: 13 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"errors"
"fmt"
)

var (
Expand Down Expand Up @@ -144,6 +145,18 @@ func (o Option[T]) IfNoneWithError(f func() error) error {
return f()
}

func (o Option[T]) String() string {
if o.IsNone() {
return "None[]"
}

v := o.Unwrap()
if stringer, ok := interface{}(v).(fmt.Stringer); ok {
return fmt.Sprintf("Some[%s]", stringer)
}
return fmt.Sprintf("Some[%v]", v)
}

// Map converts given Option value to another Option value according to the mapper function.
// If given Option value is None, this also returns None.
func Map[T, U any](option Option[T], mapper func(v T) U) Option[U] {
Expand Down
15 changes: 15 additions & 0 deletions option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,3 +553,18 @@ func TestOption_MarshalJSON_shouldHandleOmitemptyCorrectly(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, string(marshal), `{"normalVal":null}`)
}

type MyStringer struct {
}

func (m *MyStringer) String() string {
return "mystr"
}

func TestOption_String(t *testing.T) {
assert.Equal(t, "Some[123]", Some[int](123).String())
assert.Equal(t, "None[]", None[int]().String())

assert.Equal(t, "Some[mystr]", Some[*MyStringer](&MyStringer{}).String())
assert.Equal(t, "None[]", None[*MyStringer]().String())
}

0 comments on commit e1e26cc

Please sign in to comment.