2013-02-06 106 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

謝謝!很有幫助。 –