ast_print.go 735 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "go/ast"
  6. "go/parser"
  7. "go/printer"
  8. "go/token"
  9. )
  10. func main() {
  11. // src is the input for which we want to print the AST.
  12. src := `
  13. package main
  14. func hello(a, b Any, rest ...Any) Any {
  15. return a
  16. }
  17. func main() {
  18. f := 10
  19. f.(func(int)Any)
  20. }
  21. `
  22. // Create the AST by parsing src.
  23. fset := token.NewFileSet() // positions are relative to fset
  24. f, err := parser.ParseFile(fset, "", src, 0)
  25. if err != nil {
  26. panic(err)
  27. }
  28. // (f.Decls[0].(*ast.GenDecl)).Specs[0].Name.Obj = nil
  29. // ((f.Decls[0].(*ast.GenDecl)).Specs[0].(*ast.TypeSpec).Name.Obj) = nil
  30. // f.Imports = nil
  31. ast.Print(fset, f)
  32. // Print the AST.
  33. var buf bytes.Buffer
  34. printer.Fprint(&buf, fset, f)
  35. fmt.Println(buf.String())
  36. }