Skip to content

Commit

Permalink
add NonElement() (#11)
Browse files Browse the repository at this point in the history
* add NonElement()

* lint
  • Loading branch information
muir authored Apr 16, 2022
1 parent a23e455 commit 7534b3a
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 7 deletions.
7 changes: 0 additions & 7 deletions parsetag.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,3 @@ func WithTag(tag string) FillOptArg {
o.tag = tag
}
}

func NonPointer(t reflect.Type) reflect.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
29 changes: 29 additions & 0 deletions simple.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package reflectutils

import (
"reflect"
)

// NonPointer unwraps pointer types until a type that isn't
// a pointer is found.
func NonPointer(t reflect.Type) reflect.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}

// NonElement unwraps pointers, slices, arrays, and maps until
// it finds a type that doesn't support Elem. It returns that
// type.
func NonElement(t reflect.Type) reflect.Type {
for {
//nolint:exhaustive // deliberately
switch t.Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Slice:
t = t.Elem()
default:
return t
}
}
}
21 changes: 21 additions & 0 deletions simple_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package reflectutils_test

import (
"reflect"
"testing"

"github.com/muir/reflectutils"

"github.com/stretchr/testify/assert"
)

func TestNonElement(t *testing.T) {
a := []map[string][3]int{
{
"foo": {8, 3, 9},
},
}
got := reflectutils.NonElement(reflect.TypeOf(&a)).String()
t.Log(got)
assert.Equal(t, reflect.Int.String(), reflectutils.NonElement(reflect.TypeOf(&a)).String())
}

0 comments on commit 7534b3a

Please sign in to comment.