Created
February 7, 2019 12:51
-
-
Save mpppk/f3bc337753d7122cfbbf9954ee2d41c4 to your computer and use it in GitHub Desktop.
find return types of specified name method
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
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