Skip to content

Commit e3423a4

Browse files
committed
fix: FromNillable
Converts receiver method to constructor method.
1 parent cdd85a1 commit e3423a4

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

option.go

+8-8
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,14 @@ func None[T any]() Option[T] {
5656
return map[bool]T{}
5757
}
5858

59+
// FromNillable converts a nillable value to an Option.
60+
func FromNillable[T any](v *T) Option[T] {
61+
if v == nil {
62+
return None[T]()
63+
}
64+
return Some(*v)
65+
}
66+
5967
// IsSome returns whether the Option has a value or not.
6068
func (o Option[T]) IsSome() bool {
6169
return len(o) != 0
@@ -234,11 +242,3 @@ func (o *Option[T]) UnmarshalJSON(data []byte) error {
234242
*o = Some(v)
235243
return nil
236244
}
237-
238-
// FromNillable converts a nillable value to an Option.
239-
func (o Option[T]) FromNillable(v *T) Option[T] {
240-
if v == nil {
241-
return None[T]()
242-
}
243-
return Some(*v)
244-
}

option_test.go

+15-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"time"
99

1010
"github.com/stretchr/testify/assert"
11-
"github.com/tapp-ai/go-optional-v2"
11+
optionalv2 "github.com/tapp-ai/go-optional-v2"
1212
)
1313

1414
// Custom type for testing fmt.Stringer interface
@@ -34,6 +34,20 @@ func TestOption(t *testing.T) {
3434
assert.True(t, optNone.IsNone())
3535
})
3636

37+
// Test FromNillable method
38+
t.Run("FromNillable", func(t *testing.T) {
39+
var value *int = nil
40+
opt := optionalv2.FromNillable(value)
41+
assert.False(t, opt.IsSome())
42+
assert.True(t, opt.IsNone())
43+
44+
value = new(int)
45+
*value = 42
46+
opt = optionalv2.FromNillable(value)
47+
assert.True(t, opt.IsSome())
48+
assert.Equal(t, 42, opt.Unwrap())
49+
})
50+
3751
// Test Unwrap and UnwrapAsPtr methods
3852
t.Run("UnwrapMethods", func(t *testing.T) {
3953
optSome := optionalv2.Some("Hello")

0 commit comments

Comments
 (0)