Standard library / go/printer

go/printer.Config.Fprint()

Print a supported syntax node using configured mode, tab width and indentation. Positions refer to the supplied file set. Expected stdout: '1 + 2\n'.

Formal Syntax & Structure

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

Parameters & Attributes

NameTypeDescription
outputio.WriterDestination writer for printed source.
fset*token.FileSetFile set used to parse source.
nodeanySupported AST node or node list to print.

Return Value

error

Parsing or setting error; nil on success.

Working Example

Example Snippetgo
package main
import (  "bytes"  "fmt"  "go/parser"  "go/printer"  "go/token")
func check(e error) {  if e != nil {    panic(e)  }}
func main() {  fs := token.NewFileSet()  e, err := parser.ParseExprFrom(fs, "demo.go", "1+2", 0)  check(err)  var b bytes.Buffer  cfg := printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}  check(cfg.Fprint(&b, fs, e))  fmt.Println(b.String())}
Go Reference