英文:
Is there a built-in way to recursively print a tree?
问题
我正在学习Go,并且正在寻找一种打印AST的方法(参考Ruslan的优秀教程Let's Build a Simple Interpreter)。
我使用以下代码打印根节点:
tree := par.Parse()
fmt.Printf("\nParse Tree:\n%#v\n", tree)
打印结果如下:
Parse Tree:
&Node.Program{name:"PART10AST", block:(*Node.Block)(0x11b32160)}
有没有一种递归打印节点及其所有子节点的方法?类似于:
&Node.Program{name:"PART10AST", block:(*Node.Block{decl: *Node.declarations{...}, comp: *Node.Compound{...}})}
Go语言本身是否提供了这种功能?Node
是一个接口,用于多种不同类型的struct
,这些struct
存储数据和/或更多的Node
。
英文:
I am learning Go and looking for a way to print my AST (For reference, I'm following along with Ruslan's excellent Let's Build a Simple Interpreter).
I am printing the root with the following:
tree := par.Parse()
fmt.Printf("\nParse Tree:\n%#v\n", tree)
Which prints:
Parse Tree:
&Node.Program{name:"PART10AST", block:(*Node.Block)(0x11b32160)}
Is there a way to recursively print a node, and all child nodes? Something to the effect of:
&Node.Program{name:"PART10AST", block:(*Node.Block{decl: *Node.declarations{...}, comp: *Node.Compound{...}})}
Is this functionality built in to Go in any way? Node
is an interface for several different types of struct
s which store data and/or more Node
s.
答案1
得分: 4
你正在寻找 ast.Fprint,可以在 https://godoc.org/go/ast#Fprint 找到相关信息。
英文:
You are looking for ast.Fprint, https://godoc.org/go/ast#Fprint
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论