diff --git a/option.go b/option.go index ce809b1..f30cc9a 100644 --- a/option.go +++ b/option.go @@ -56,6 +56,14 @@ func None[T any]() Option[T] { return map[bool]T{} } +// FromNillable converts a nillable value to an Option. +func FromNillable[T any](v *T) Option[T] { + if v == nil { + return None[T]() + } + return Some(*v) +} + // IsSome returns whether the Option has a value or not. func (o Option[T]) IsSome() bool { return len(o) != 0 @@ -234,11 +242,3 @@ func (o *Option[T]) UnmarshalJSON(data []byte) error { *o = Some(v) return nil } - -// FromNillable converts a nillable value to an Option. -func (o Option[T]) FromNillable(v *T) Option[T] { - if v == nil { - return None[T]() - } - return Some(*v) -} diff --git a/option_test.go b/option_test.go index eb2bb80..9c9e6ee 100644 --- a/option_test.go +++ b/option_test.go @@ -8,7 +8,7 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/tapp-ai/go-optional-v2" + optionalv2 "github.com/tapp-ai/go-optional-v2" ) // Custom type for testing fmt.Stringer interface @@ -34,6 +34,20 @@ func TestOption(t *testing.T) { assert.True(t, optNone.IsNone()) }) + // Test FromNillable method + t.Run("FromNillable", func(t *testing.T) { + var value *int = nil + opt := optionalv2.FromNillable(value) + assert.False(t, opt.IsSome()) + assert.True(t, opt.IsNone()) + + value = new(int) + *value = 42 + opt = optionalv2.FromNillable(value) + assert.True(t, opt.IsSome()) + assert.Equal(t, 42, opt.Unwrap()) + }) + // Test Unwrap and UnwrapAsPtr methods t.Run("UnwrapMethods", func(t *testing.T) { optSome := optionalv2.Some("Hello")