Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add NonElement() #11

Merged
merged 2 commits into from
Apr 16, 2022
Merged
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
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())
}