Skip to content

Instantly share code, notes, and snippets.

@mpppk
Created February 7, 2019 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpppk/f3bc337753d7122cfbbf9954ee2d41c4 to your computer and use it in GitHub Desktop.
Save mpppk/f3bc337753d7122cfbbf9954ee2d41c4 to your computer and use it in GitHub Desktop.
find return types of specified name method
package main
import (
"fmt"
"go/ast"
"go/parser"
)
import "golang.org/x/tools/go/loader"
func main() {
source := `
package main
import "fmt"
type s struct{}
func (s s)Println(x string) {}
func increment(v int) int {
return v + 1
}
func main(){
fmt.Println("xxx")
{
fmt := s{}
fmt.Println("yyy")
}
fmt.Println("xxx")
}
`
lo := loader.Config{ParserMode: parser.ParseComments}
astf, err := lo.ParseFile("main.go", source)
if err != nil {
panic(err)
}
lo.CreateFromFiles("main", astf)
prog, err := lo.Load()
if err != nil {
panic(err)
}
targetPkgName := "fmt"
targetFuncName := "Println"
targetPkg := prog.Package(targetPkgName)
fmt.Println(targetPkg)
var targetSelectorExpr *ast.SelectorExpr
for _, file := range targetPkg.Files {
ast.FileExports(file)
for _, decl := range file.Decls {
if funcDecl, ok := decl.(*ast.FuncDecl); ok {
if funcDecl.Name.Name == targetFuncName {
results := funcDecl.Type.Results.List
for _, result := range results {
if typeIdent, ok := result.Type.(*ast.Ident); ok {
fmt.Println(typeIdent.Name)
}
}
}
}
}
}
_ = ast.Print(nil, targetSelectorExpr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment