Code Examples
package main
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/printer"
"go/token"
"strings"
)
func parseFunc(filename, functionname string) (fun *ast.FuncDecl, fset *token.FileSet) {
fset = token.NewFileSet()
if file, err := parser.ParseFile(fset, filename, nil, 0); err == nil {
for _, d := range file.Decls {
if f, ok := d.(*ast.FuncDecl); ok && f.Name.Name == functionname {
fun = f
return
}
}
}
panic("function not found")
}
func printSelf() {
// Parse source file and extract the AST without comments for
// this function, with position information referring to the
// file set fset.
funcAST, fset := parseFunc("example_test.go", "printSelf")
// Print the function body into buffer buf.
// The file set is provided to the printer so that it knows
// about the original source formatting and can add additional
// line breaks where they were present in the source.
var buf bytes.Buffer
printer.Fprint(&buf, fset, funcAST.Body)
// Remove braces {} enclosing the function body, unindent,
// and trim leading and trailing white space.
s := buf.String()
s = s[1 : len(s)-1]
s = strings.TrimSpace(strings.ReplaceAll(s, "\n\t", "\n"))
// Print the cleaned-up body text to stdout.
fmt.Println(s)
}
func main() {
printSelf()
}
Package-Level Type Names (total 3)
/* sort by: | */
A CommentedNode bundles an AST node and corresponding comments.
It may be provided as argument to any of the [Fprint] functions.Comments[]*ast.CommentGroup // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt
A Config node controls the output of Fprint. // default: 0 (all code is indented at least by this much) // default: 0 // default: 8 Fprint "pretty-prints" an AST node to output for a given configuration cfg.
Position information is interpreted relative to the file set fset.
The node type must be *[ast.File], *[CommentedNode], [][ast.Decl], [][ast.Stmt],
or assignment-compatible to [ast.Expr], [ast.Decl], [ast.Spec], or [ast.Stmt].
Fprint "pretty-prints" an AST node to output.
It calls [Config.Fprint] with default settings.
Note that gofmt uses tabs for indentation but spaces for alignment;
use format.Node (package go/format) for output that matches gofmt.
Package-Level Constants (total 4)
const RawFormatMode = 1 // do not use a tabwriter; if set, UseSpaces is ignored
const SourcePosMode = 8 // emit //line directives to preserve original source positions
const TabIndentMode = 2 // use tabs for indentation independent of UseSpaces
const UseSpacesMode = 4 // use spaces instead of tabs for alignment
The pages are generated with Goldsv0.7.0-preview. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.