當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


GO Node用法及代碼示例

GO語言"go/format"包中"Node"函數的用法及代碼示例。

用法:

func Node(dst io.Writer, fset *token.FileSet, node any) error

節點以規範的 gofmt 樣式格式化節點並將結果寫入 dst。

節點類型必須是 *ast.File、*printer CommentedNode []ast.Decl、[]ast.Stmt 或 assignment-compatible 到 ast.Expr、ast.Decl、ast.Spec 或 ast.Stmt。節點不修改節點。對於表示部分源文件的節點(例如,如果節點不是 *ast.File 或 *printer CommentedNode 不包裝 *ast.File),導入不會排序。

該函數可能會提前返回(在寫入整個結果之前)並返回格式錯誤,例如由於 AST 不正確。

例子:

package main

import (
    "bytes"
    "fmt"
    "go/format"
    "go/parser"
    "go/token"
    "log"
)

func main() {
    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 = format.Node(&buf, fset, node)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(buf.String())

}

輸出:

(6 + 2*3) / 4

相關用法


注:本文由純淨天空篩選整理自golang.google.cn大神的英文原創作品 Node。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。