Skip to content

Commit

Permalink
feat: Adds support for creating options from pointers
Browse files Browse the repository at this point in the history
A new function NewOptionFromPointer was added to support creating options from pointers. This function takes in a pointer and returns an Option type where None is returned if the pointer is null and Some if the pointer is valid
  • Loading branch information
martianoff committed Jun 30, 2024
1 parent d136fb3 commit 06b20c6
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ Set an empty value if v is nil, otherwise set non-empty value
v := option.NewOption[int](10)
```

Convert pointer to an object to an option
```
v := option.NewOptionFromPointer[Car](nil) // None[Car]
v := option.NewOptionFromPointer[Car](&Car{}) // Some[Car]
```

Transform underlying value of option to non option value
```
import "github.com/martianoff/go-option"
Expand Down
7 changes: 7 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@ func NewOption[T any](o T) Option[T] {
return Option[T]{optSome[T]{o}}
}

func NewOptionFromPointer[T any](o *T) Option[T] {
if o == nil {
return None[T]()
}
return Some[T](*o)
}

func Map[T1, T2 any](opt Option[T1], mapper func(T1) T2) Option[T2] {
if opt.NonEmpty() {
return Option[T2]{optSome[T2]{mapper(opt.Get())}}
Expand Down
33 changes: 33 additions & 0 deletions option_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,39 @@ func TestToOption(t *testing.T) {
}
}

func TestNewOptionFromPointer(t *testing.T) {
type T = int

cases := []struct {
name string
input *T
expected Option[T]
}{
{
name: "Test with nil pointer should return None",
input: nil,
expected: None[T](),
},
{
name: "Test with valid pointer should return Some",
input: func() *T {
var v T = 5
return &v
}(),
expected: Some[T](5),
},
}

for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
result := NewOptionFromPointer(tt.input)
if !result.Equal(tt.expected) {
t.Errorf("Expected: %v, got: %v", tt.expected, result)
}
})
}
}

func TestOptionEqual(t *testing.T) {
type T = int

Expand Down

0 comments on commit 06b20c6

Please sign in to comment.