Standard library / go/format

go/format.Source()

Format valid Go files or fragments in canonical gofmt style; reports syntax errors, does not type-check. Full-file imports are sorted. Expected stdout: '"package p\\n\\nvar x = 1 + 2\\n"\n'.

Formal Syntax & Structure

go syntaxgo
func Source(src []byte) ([]byte, error)

Parameters & Attributes

NameTypeDescription
src[]byteSource bytes containing a file, declarations or statements.

Return Value

([]byte, error)

Format valid Go files or fragments in canonical gofmt style; reports syntax errors, does not type-check.

Working Example

Example Snippetgo
package main
import (  "fmt"  "go/format")
func check(e error) {  if e != nil {    panic(e)  }}
func main() { b, e := format.Source([]byte("package p\nvar x=1+2\n")); check(e); fmt.Printf("%q\n", b) }
Go Reference