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

lang/go: Add TypeName.IsPointer() #66

Merged
merged 1 commit into from
Nov 14, 2019
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
16 changes: 10 additions & 6 deletions lang/go/type_name.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,21 @@ func (n TypeName) Key() TypeName {
return TypeName(parts[1])
}

// IsPointer reports whether TypeName n is a pointer type, slice or a map.
func (n TypeName) IsPointer() bool {
ns := string(n)
return strings.HasPrefix(ns, "*") ||
strings.HasPrefix(ns, "[") ||
strings.HasPrefix(ns, "map[")
}

// Pointer converts TypeName n to it's pointer type. If n is already a pointer,
// slice, or map, it is returned unmodified.
func (n TypeName) Pointer() TypeName {
ns := string(n)
if strings.HasPrefix(ns, "*") ||
strings.HasPrefix(ns, "[") ||
strings.HasPrefix(ns, "map[") {
if n.IsPointer() {
return n
}

return TypeName("*" + ns)
return TypeName("*" + string(n))
}

// Value converts TypeName n to it's value type. If n is already a value type,
Expand Down
24 changes: 24 additions & 0 deletions lang/go/type_name_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,11 @@ func TestTypeName(t *testing.T) {
assert.Equal(t, tc.key, tn.Key().String())
})

t.Run("IsPointer", func(t *testing.T) {
t.Parallel()
assert.Equal(t, tc.ptr == tc.in, tn.IsPointer())
})

t.Run("Pointer", func(t *testing.T) {
t.Parallel()
assert.Equal(t, tc.ptr, tn.Pointer().String())
Expand Down Expand Up @@ -305,6 +310,25 @@ func ExampleTypeName_Key() {
// string
}

func ExampleTypeName_IsPointer() {
types := []string{
"int",
"*my.Type",
"[]string",
"map[string]*io.Reader",
}

for _, t := range types {
fmt.Println(TypeName(t).IsPointer())
}

// Output:
// false
// true
// true
// true
}

func ExampleTypeName_Pointer() {
types := []string{
"int",
Expand Down