?
本文檔使用 php中文網(wǎng)手冊 發(fā)布
import "go/format"
Overview
Index
Examples
包格式實現(xiàn)Go源的標(biāo)準(zhǔn)格式。
func Node(dst io.Writer, fset *token.FileSet, node interface{}) error
func Source(src []byte) ([]byte, error)
節(jié)點(diǎn)
format.go internal.go
func Node(dst io.Writer, fset *token.FileSet, node interface{}) error
節(jié)點(diǎn)以規(guī)范的gofmt樣式格式化節(jié)點(diǎn)并將結(jié)果寫入dst。
節(jié)點(diǎn)類型必須是* ast.File,* printer.CommentedNode,[] ast.Decl,[] ast.Stmt或賦值與ast.Expr,ast.Decl,ast.Spec或ast.Stmt兼容。節(jié)點(diǎn)不修改節(jié)點(diǎn)。對于表示部分源文件的節(jié)點(diǎn)(即,如果節(jié)點(diǎn)不是* ast.File或* printer.CommentedNode不包裝* ast.File),導(dǎo)入不會被排序。
該函數(shù)可能會返回提前(在寫入整個結(jié)果之前)并返回格式錯誤,例如由于錯誤的AST。
代碼:
const expr = "(6+2*3)/4"// parser.ParseExpr parses the argument and returns the// corresponding ast.Node.node, err := parser.ParseExpr(expr)if err != nil { log.Fatal(err)}// Create a FileSet for node. Since the node does not come// from a real source file, fset will be empty.fset := token.NewFileSet()var buf bytes.Buffer err = Node(&buf, fset, node)if err != nil { log.Fatal(err)}fmt.Println(buf.String())
輸出:
(6 + 2*3) / 4
func Source(src []byte) ([]byte, error)
source格式的src采用規(guī)范的gofmt風(fēng)格,并返回結(jié)果或(I / O或語法)錯誤。src應(yīng)該是一個語法正確的Go源文件,或者一個Go聲明或語句的列表。
如果src是部分源文件,則將src的前導(dǎo)空格和尾部空格應(yīng)用于結(jié)果(以便它與src具有相同的前導(dǎo)和尾隨空格),并且結(jié)果的縮進(jìn)量與src的第一行相同包含代碼。導(dǎo)入不針對部分源文件進(jìn)行排序。