-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* add NonElement() * lint
- Loading branch information
Showing
3 changed files
with
50 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | ||
} |