?
This document uses PHP Chinese website manual Release
import "go/printer"
Overview
Index
Examples
Package printer實(shí)現(xiàn)了AST節(jié)點(diǎn)的打印。
func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error
type CommentedNode
type Config
func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{}) error
type Mode
Fprint
nodes.go printer.go
func Fprint(output io.Writer, fset *token.FileSet, node interface{}) error
Fprint“漂亮地”輸出一個(gè)AST節(jié)點(diǎn)。它使用默認(rèn)設(shè)置調(diào)用Config.Fprint。請注意,gofmt使用制表符縮進(jìn)但使用空格對齊; 使用format.Node(包go /格式)來匹配gofmt的輸出。
代碼:
// 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", "ExampleFprint")// 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.Replace(s, "\n\t", "\n", -1))// Print the cleaned-up body text to stdout.fmt.Println(s)
輸出:
funcAST, fset := parseFunc("example_test.go", "ExampleFprint")var buf bytes.Buffer printer.Fprint(&buf, fset, funcAST.Body)s := buf.String()s = s[1 : len(s)-1]s = strings.TrimSpace(strings.Replace(s, "\n\t", "\n", -1))fmt.Println(s)
CommentedNode捆綁了一個(gè)AST節(jié)點(diǎn)和相應(yīng)的注釋。它可以作為任何Fprint函數(shù)的參數(shù)提供。
type CommentedNode struct { Node interface{} // *ast.File, or ast.Expr, ast.Decl, ast.Spec, or ast.Stmt Comments []*ast.CommentGroup}
Config節(jié)點(diǎn)控制Fprint的輸出。
type Config struct { Mode Mode // default: 0 Tabwidth int // default: 8 Indent int // default: 0 (all code is indented at least by this much)}
func (cfg *Config) Fprint(output io.Writer, fset *token.FileSet, node interface{}) error
Fprint“漂亮地打印”AST節(jié)點(diǎn)以輸出給定的配置cfg。位置信息相對于文件集fset進(jìn)行解釋。節(jié)點(diǎn)類型必須為ast.Expr,ast.Decl,ast.Spec或ast.Stmt的* ast.File,* CommentedNode,[] ast.Decl,[] ast.Stmt或賦值兼容。
Mode值是一組標(biāo)志(或0)。他們控制打印。
type Mode uint
const ( RawFormat Mode = 1 << iota // do not use a tabwriter; if set, UseSpaces is ignored TabIndent // use tabs for indentation independent of UseSpaces UseSpaces // use spaces instead of tabs for alignment SourcePos // emit //line directives to preserve original source positions)