Skip to content

Instantly share code, notes, and snippets.

@junftnt
Forked from zupzup/main.go
Created September 3, 2019 21:52
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 junftnt/dcab90cf3b6443571573db1f6d839da8 to your computer and use it in GitHub Desktop.
Save junftnt/dcab90cf3b6443571573db1f6d839da8 to your computer and use it in GitHub Desktop.
Example for Basic AST Traversal in Go
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()
}
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, ", ")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment