Generate Go source code

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

I found go / parser to generate the AST version of the Go source file, but could not find a way to generate the Go source from the AST.

+5
source share
1 answer

To convert the AST to its original form, you 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 )


Conclusion:

package main

func main() {
        println("Hello, World!")
}
+15
source

All Articles