2013-02-06 108 views
5

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

我发现去/解析器生成AST形式的Go源文件,但无法找到一种方法来从AST生成Go源。

回答

15

要将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) 

} 

(也here


输出:

package main 

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

谢谢!很有帮助。 –