有没有内置的方法可以递归打印一棵树?

huangapple go评论83阅读模式
英文:

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 structs which store data and/or more Nodes.

答案1

得分: 4

你正在寻找 ast.Fprint,可以在 https://godoc.org/go/ast#Fprint 找到相关信息。

英文:

You are looking for ast.Fprint, https://godoc.org/go/ast#Fprint

huangapple
  • 本文由 发表于 2016年12月14日 04:33:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/41130075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定