Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,14 +252,19 @@ func (o Option[T]) IsZero() bool {
return true
}

// A nil pointer can implement zeroer through a value-receiver method,
// which cannot be called without dereferencing the nil pointer.
rv := reflect.ValueOf(o.value)
if !rv.IsValid() || rv.Kind() == reflect.Ptr && rv.IsNil() {
return true
}

var v any = o.value
if v, ok := v.(zeroer); ok {
return v.IsZero()
}

// a nil interface yields an invalid reflect.Value, on which IsZero panics
rv := reflect.ValueOf(o.value)
return !rv.IsValid() || rv.IsZero()
return rv.IsZero()
}

// MarshalText implements the encoding.TextMarshaler interface.
Expand Down
23 changes: 23 additions & 0 deletions option_nil_zero_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package mo

import (
"testing"
"time"
)

func TestOptionIsZeroNilZeroer(t *testing.T) {
var value *time.Time
if !Some(value).IsZero() {
t.Error("a nil time pointer should be zero")
}
if !Some[any](value).IsZero() {
t.Error("an interface holding a nil time pointer should be zero")
}
if !Some(&time.Time{}).IsZero() {
t.Error("a pointer to zero time should still use time.IsZero")
}
nonzero := time.Unix(1, 0)
if Some(&nonzero).IsZero() {
t.Error("a nonzero time pointer should not be zero")
}
}