version: 1.10

package format

import "go/format"


Package format implements standard formatting of Go source.



Package files

format.go internal.go

func Node

  1. func Node(dst io.Writer, fset *token.FileSet, node interface{}) error

Node formats node in canonical gofmt style and writes the result to dst.

The node type must be ast.File, printer.CommentedNode, []ast.Decl, []ast.Stmt,
or assignment-compatible to ast.Expr, ast.Decl, ast.Spec, or ast.Stmt. Node does
not modify node. Imports are not sorted for nodes representing partial source
files (for instance, if the node is not an ast.File or a printer.CommentedNode
not wrapping an *ast.File).

The function may return early (before the entire result is written) and return a
formatting error, for instance due to an incorrect AST.


  1. const expr = "(6+2*3)/4"
  2. // parser.ParseExpr parses the argument and returns the
  3. // corresponding ast.Node.
  4. node, err := parser.ParseExpr(expr)
  5. if err != nil {
  6. log.Fatal(err)
  7. }
  8. // Create a FileSet for node. Since the node does not come
  9. // from a real source file, fset will be empty.
  10. fset := token.NewFileSet()
  11. var buf bytes.Buffer
  12. err = Node(&buf, fset, node)
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16. fmt.Println(buf.String())
  17. // Output: (6 + 2*3) / 4

func Source

  1. func Source(src []byte) ([]byte, error)

Source formats src in canonical gofmt style and returns the result or an (I/O or
syntax) error. src is expected to be a syntactically correct Go source file, or
a list of Go declarations or statements.

If src is a partial source file, the leading and trailing space of src is
applied to the result (such that it has the same leading and trailing space as
src), and the result is indented by the same amount as the first line of src
containing code. Imports are not sorted for partial source files.

Caution: Tools relying on consistent formatting based on the installed version
of gofmt (for instance, such as for presubmit checks) should execute that gofmt
binary instead of calling Source.