| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
package main |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"go/ast" |
| 12 |
"go/parser" |
| 13 |
"go/token" |
| 14 |
"go/types" |
| 15 |
"log" |
| 16 |
) |
| 17 |
|
| 18 |
const src = ` |
| 19 |
//!+input |
| 20 |
package p |
| 21 |
|
| 22 |
type Numeric interface{ |
| 23 |
~int | ~float64 // etc... |
| 24 |
} |
| 25 |
|
| 26 |
func Square[N Numeric](n N) N { |
| 27 |
return n*n |
| 28 |
} |
| 29 |
|
| 30 |
type Findable interface { |
| 31 |
comparable |
| 32 |
} |
| 33 |
|
| 34 |
func Find[T Findable](s []T, v T) int { |
| 35 |
for i, v2 := range s { |
| 36 |
if v2 == v { |
| 37 |
return i |
| 38 |
} |
| 39 |
} |
| 40 |
return -1 |
| 41 |
} |
| 42 |
//!-input |
| 43 |
` |
| 44 |
|
| 45 |
|
| 46 |
func PrintNumericSyntax(fset *token.FileSet, file *ast.File) { |
| 47 |
|
| 48 |
node := file.Scope.Lookup("Numeric").Decl.(*ast.TypeSpec) |
| 49 |
|
| 50 |
embedded := node.Type.(*ast.InterfaceType).Methods.List[0].Type |
| 51 |
|
| 52 |
ast.Print(fset, embedded) |
| 53 |
} |
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
func PrintInterfaceTypes(fset *token.FileSet, file *ast.File) error { |
| 84 |
conf := types.Config{} |
| 85 |
pkg, err := conf.Check("hello", fset, []*ast.File{file}, nil) |
| 86 |
if err != nil { |
| 87 |
return err |
| 88 |
} |
| 89 |
|
| 90 |
PrintIface(pkg, "Numeric") |
| 91 |
PrintIface(pkg, "Findable") |
| 92 |
|
| 93 |
return nil |
| 94 |
} |
| 95 |
|
| 96 |
func PrintIface(pkg *types.Package, name string) { |
| 97 |
obj := pkg.Scope().Lookup(name) |
| 98 |
fmt.Println(obj) |
| 99 |
iface := obj.Type().Underlying().(*types.Interface) |
| 100 |
for i := 0; i < iface.NumEmbeddeds(); i++ { |
| 101 |
fmt.Printf("\tembeded: %s\n", iface.EmbeddedType(i)) |
| 102 |
} |
| 103 |
for i := 0; i < iface.NumMethods(); i++ { |
| 104 |
fmt.Printf("\tembeded: %s\n", iface.EmbeddedType(i)) |
| 105 |
} |
| 106 |
fmt.Printf("\tIsComparable(): %t\n", iface.IsComparable()) |
| 107 |
fmt.Printf("\tIsMethodSet(): %t\n", iface.IsMethodSet()) |
| 108 |
} |
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
func main() { |
| 126 |
|
| 127 |
fset := token.NewFileSet() |
| 128 |
f, err := parser.ParseFile(fset, "p.go", src, 0) |
| 129 |
if err != nil { |
| 130 |
log.Fatal(err) |
| 131 |
} |
| 132 |
fmt.Println("=== PrintNumericSyntax ==") |
| 133 |
PrintNumericSyntax(fset, f) |
| 134 |
fmt.Println("=== PrintInterfaceTypes ==") |
| 135 |
if err := PrintInterfaceTypes(fset, f); err != nil { |
| 136 |
log.Fatal(err) |
| 137 |
} |
| 138 |
} |