Skip to content

Commit

Permalink
Fix Cast to interfaces
Browse files Browse the repository at this point in the history
  • Loading branch information
totemcaf committed Aug 19, 2022
1 parent ca2637d commit 0351561
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
7 changes: 4 additions & 3 deletions nils/nils.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,13 @@ func Copy[T any](value *T) *T {
return &t
}

func CastOrNil[T any](value any) *T {
func CastOrNil[T any](value any) T {
if value == nil {
return nil
var t T
return t
}

t, ok := value.(*T)
t, ok := value.(T)

if !ok {
panic("cannot cast value to type " + reflect.TypeOf(value).String())
Expand Down
21 changes: 18 additions & 3 deletions nils/nils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,31 @@ func Test_Copy_returns_copied_value_for_not_nil(t *testing.T) {
func Test_CastOrNil_returns_nil_for_nil(t *testing.T) {
var aNil *string = nil

assert.Equal(t, aNil, CastOrNil[string](aNil))
assert.Equal(t, aNil, CastOrNil[*string](aNil))
}

type ISample interface {
GetValue() string
}

type sample struct {
aValue string
}

func (s *sample) GetValue() string {
return s.aValue
}

func Test_CastOrNil_returns_casted_value_for_not_nil(t *testing.T) {
var aValue sample = sample{aString}

assert.Equal(t, &aValue, CastOrNil[sample](&aValue))
assert.IsType(t, &sample{}, CastOrNil[sample](&aValue))
assert.Equal(t, &aValue, CastOrNil[*sample](&aValue))
assert.IsType(t, &sample{}, CastOrNil[*sample](&aValue))
}

func Test_CastOrNil_returns_casted_value_for_interfaces(t *testing.T) {
var aValue sample = sample{aString}

assert.Equal(t, &aValue, CastOrNil[ISample](&aValue))
assert.IsType(t, &sample{}, CastOrNil[ISample](&aValue))
}

0 comments on commit 0351561

Please sign in to comment.