生成Go源代码

Gün*_*uer 5 go generated-code

我正在寻找一种生成Go源代码的方法.

我发现go/parser生成一个AST形式的Go源文件,但是找不到从AST生成Go源的方法.

zzz*_*zzz 17

要将AST转换为源表单,可以使用go/printer包.

示例(另一个示例的改编形式)

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)

}
Run Code Online (Sandbox Code Playgroud)

(也在这里)


输出:

package main

func main() {
        println("Hello, World!")
}
Run Code Online (Sandbox Code Playgroud)