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.
Running the code generatorEnsure that the main program from the codegen_builder.go file and the templates are in the same directory. Then run go run codegen_builder.go in your terminal. Now the program will generate code with the help of the templates and output it in the ./tmp directory.
go generate is a tool that comes with the go command. You write go generate directives in your source code and then run the directives by calling go generate on the command line (or using your IDE).
Running Code During development the go run tool is a convenient way to try out your code. It's essentially a shortcut that compiles your code, creates an executable binary in your /tmp directory, and then runs this binary in one step.
Go programs are organized into packages. A package is a collection of source files in the same directory that are compiled together. Functions, types, variables, and constants defined in one source file are visible to all other source files within the same package. A repository contains one or more modules.
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!")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With