-
-
Save seafitliu/a1e65313c99eee901afde1f91e7a5883 to your computer and use it in GitHub Desktop.
Revisions
-
zupzup created this gist
Jul 14, 2017 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,63 @@ package main import ( "fmt" "go/ast" "go/parser" "go/printer" "go/token" "log" "os" ) func main() { fset := token.NewFileSet() node, err := parser.ParseFile(fset, "test.go", nil, parser.ParseComments) if err != nil { log.Fatal(err) } fmt.Println("########### Manual Iteration ###########") fmt.Println("Imports:") for _, i := range node.Imports { fmt.Println(i.Path.Value) } fmt.Println("Comments:") for _, c := range node.Comments { fmt.Print(c.Text()) } fmt.Println("Functions:") for _, f := range node.Decls { fn, ok := f.(*ast.FuncDecl) if !ok { continue } fmt.Println(fn.Name.Name) } fmt.Println("########### Inspect ###########") ast.Inspect(node, func(n ast.Node) bool { // Find Return Statements ret, ok := n.(*ast.ReturnStmt) if ok { fmt.Printf("return statement found on line %d:\n\t", fset.Position(ret.Pos()).Line) printer.Fprint(os.Stdout, fset, ret) return true } // Find Functions fn, ok := n.(*ast.FuncDecl) if ok { var exported string if fn.Name.IsExported() { exported = "exported " } fmt.Printf("%sfunction declaration found on line %d: \n\t%s\n", exported, fset.Position(fn.Pos()).Line, fn.Name.Name) return true } return true }) fmt.Println() } This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,21 @@ package main import "fmt" import "strings" func main() { hello := "Hello" world := "World" words := []string{hello, world} SayHello(words) } // SayHello says Hello func SayHello(words []string) { fmt.Println(joinStrings(words)) } // joinStrings joins strings func joinStrings(words []string) string { return strings.Join(words, ", ") }