diff --git a/option.go b/option.go index 9bad6325..67203578 100644 --- a/option.go +++ b/option.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "errors" + "fmt" ) var ( @@ -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] { diff --git a/option_test.go b/option_test.go index b9a61214..11af1726 100644 --- a/option_test.go +++ b/option_test.go @@ -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()) +}