10

I am looking for a way to generate Go source code.

I found go/parser to generate an AST form a Go source file but couldn't find a way to generate Go source from AST.

mindriot
  • 5,413
  • 1
  • 25
  • 34
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567

1 Answers1

25

To convert an AST to the source form one can use the go/printer package.

Example (adapted form of another example)

package main

import (
        "go/parser"
        "go/printer"
        "go/token"
        "os"
)

func main() {
        // src is the input for which we want to print the AST.
        src := `
package main
func main() {
        println("Hello, World!")
}
`

        // Create the AST by parsing src.
        fset := token.NewFileSet() // positions are relative to fset
        f, err := parser.ParseFile(fset, "", src, 0)
        if err != nil {
                panic(err)
        }

        printer.Fprint(os.Stdout, fset, f)

}

(also here)


Output:

package main

func main() {
        println("Hello, World!")
}
zzzz
  • 87,403
  • 16
  • 175
  • 139
  • 1
    Cant see the benefits. I could just write the string to a file and run `go fmt` on it? – C4d Aug 19 '18 at 20:59
  • @C4d I know its a few years old, but code generation. you could build up an AST programmatically, then write out a file of the results. – Matthew Curry Oct 01 '21 at 17:53