【问题标题】:Is there a built-in way to recursively print a tree?是否有递归打印树的内置方法?
【发布时间】:2016-12-13 20:33:28
【问题描述】:

我正在学习 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 是几种不同类型的structs 的接口,这些structs 存储数据和/或更多Nodes。

【问题讨论】:

  • 您没有任何内置方法来打印该数据,但如果您有权访问 Node 的属性,则可以为您的 AST 实现 printtoString 方法.

标签: go struct printing interface


【解决方案1】:

您正在寻找 ast.Fprint,https://godoc.org/go/ast#Fprint

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2019-10-28
    相关资源
    最近更新 更多