当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO Fprint用法及代码示例


GO语言"go/printer"包中"Fprint"函数的用法及代码示例。

用法:

func Fprint(output io.Writer, fset *token.FileSet, node any) error

Fprint "pretty-prints" 一个要输出的 AST 节点。它使用默认设置调用 Config.Fprint。请注意,gofmt 使用制表符进行缩进,但使用空格进行对齐;使用 format.Node (package go/format) 输出匹配 gofmt。

例子:

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 main() {
	// 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.ReplaceAll(s, "\n\t", "\n"))

	// 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.ReplaceAll(s, "\n\t", "\n"))

fmt.Println(s)

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 Fprint。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。