Skip to content

Commit

Permalink
Fixes rjeczalik#41: Add generics support for params and results
Browse files Browse the repository at this point in the history
Add support for checking if the params or result types are
instantiated with types and if so, build up the name
appropriately.
  • Loading branch information
Steve Graham committed Jun 21, 2023
1 parent 1752681 commit 52b75ee
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
19 changes: 19 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ import (
"github.com/rjeczalik/interfaces"
)

type Generic1[A any] struct {
Value A
}

type Generic2[A any, B any] struct {
Value A
Value2 B
}

type ExampleFoo int

type ExampleBar struct{}
Expand All @@ -35,6 +44,14 @@ func (ExampleBaz) D(*map[interface{}]struct{}, interface{}) (chan struct{}, []in

func (*ExampleBaz) E(*[]map[*flag.FlagSet]struct{}, [3]string) {}

func (*ExampleBaz) F(v Generic1[io.Writer]) (Generic2[io.Writer, ExampleFoo], int) {
return Generic2[io.Writer, ExampleFoo]{}, 0
}

func (*ExampleBaz) G(v Generic2[string, io.Writer]) (Generic1[int], int) {
return Generic1[int]{}, 0
}

func ExampleNew() {
i, err := interfaces.New(`github.com/rjeczalik/interfaces.ExampleBaz`)
if err != nil {
Expand All @@ -55,6 +72,8 @@ func ExampleNew() {
// C(map[string]int, *interfaces.Options, *http.Client) (chan []string, error)
// D(*map[interface{}]struct{}, interface{}) (chan struct{}, []interface{})
// E(*[]map[*flag.FlagSet]struct{}, [3]string)
// F(interfaces_test.Generic1[io.Writer]) (interfaces_test.Generic2[io.Writer, interfaces_test.ExampleFoo], int)
// G(interfaces_test.Generic2[string, io.Writer]) (interfaces_test.Generic1[int], int)
// Dependencies:
// flag
// github.com/rjeczalik/interfaces
Expand Down
7 changes: 7 additions & 0 deletions type.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@ func (typ *Type) setFromSignature(t *types.Signature) {
func (typ *Type) setFromNamed(t *types.Named) {
if typ.Name == "" {
typ.Name = t.Obj().Name()
if typeArgs := t.TypeArgs(); typeArgs != nil && typeArgs.Len() > 0 {
argValues := make([]string, typeArgs.Len())
for i := 0; i < typeArgs.Len(); i++ {
argValues[i] = typeArgs.At(i).String()
}
typ.Name = fmt.Sprintf("%s[%s]", typ.Name, strings.Join(argValues, ", "))
}
}
if typ.Package != "" || typ.ImportPath != "" {
return
Expand Down

0 comments on commit 52b75ee

Please sign in to comment.