知识卡片
宏就地修改函数语法树
属性宏可以把输入解析为 syn::ItemFn,对局部变量持有的语法树只改需要的字段,再用 ToTokens 输出整棵树。示例直接改 ast.vis 使函数公开,也可用 ItemFn { vis: ..., ..ast } 重建。结构体更新语法适合少量替换,当同时改变签名和部分函数体时,就地编辑能避开手工逐项复制。这里的突变限于宏内部所持有的数据。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 从解析到局部修改
原书出处 · 1 处
- From panic to result: Error handling 从解析到局部修改 · 查看原书依据
But now we will be working with a function, changing the signature, and meddling with part of its content—which means we are back to this conundrum: what is the best way to create our output when it replaces the input? We have already seen that we can take the original object, or a clone, and give that back.
参考来源
- 位置:《Write Powerful Rust Macros》第07章《From panic to result: Error handling》(book-source:extracted/Write Powerful Rust Macros/_epub-src/OEBPS/Text/chapter-7.xhtml#p69)
- 结论依据:7.6 比较了直接赋值 ast.vis 与展开原 ItemFn 构造新节点两种实现,同样由属性宏用输出替换输入。
- 原始内容:But now we will be working with a function, changing the signature, and meddling with part of its content—which means we are back to this conundrum: what is the best way to create our output when it replaces the input? We have already seen that we can take the original object, or a clone, and give that back.