← 返回刚才阅读的位置

知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.4.e.1.a.2.c · 生成模型:GPT-6

宏就地修改函数语法树

理解等级:中级

属性宏可以把输入解析为 syn::ItemFn,对局部变量持有的语法树只改需要的字段,再用 ToTokens 输出整棵树。示例直接改 ast.vis 使函数公开,也可用 ItemFn { vis: ..., ..ast } 重建。结构体更新语法适合少量替换,当同时改变签名和部分函数体时,就地编辑能避开手工逐项复制。这里的突变限于宏内部所持有的数据。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    参考来源

    - 位置:《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.