英文:
Generate Go source code
问题
我正在寻找一种生成Go源代码的方法。
我发现go/parser可以从Go源文件生成AST,但找不到从AST生成Go源代码的方法。
英文:
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.
答案1
得分: 25
要将AST转换为源代码形式,可以使用go/printer包。
示例(改编自另一个示例):
package main
import (
        "go/parser"
        "go/printer"
        "go/token"
        "os"
)
func main() {
        // src是我们想要打印AST的输入。
        src := `
package main
func main() {
        println("Hello, World!")
}
`
        // 通过解析src来创建AST。
        fset := token.NewFileSet() // 位置相对于fset
        f, err := parser.ParseFile(fset, "", src, 0)
        if err != nil {
                panic(err)
        }
        printer.Fprint(os.Stdout, fset, f)
}
(也可以在这里找到)
输出:
package main
func main() {
        println("Hello, World!")
}
英文:
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!")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论