知识卡片
改写签名与尾表达式
属性宏要把返回 Person 的函数改成返回 Result<Person, String>,需要同时修改签名和函数体。先匹配 ast.sig.output。省略返回类型对应 (),显式箭头后保留原类型,包括显式 -> ()。用 quote! 写出新签名,再用 syn::parse2 得到 ReturnType。然后在示例的直接尾表达式外包 Ok(..),并构造一个没有分号的表达式语句。本章演示的尾部替换适用于确有一个尾表达式的简单函数。空函数体、提前返回和复杂控制流需要另行处理。
相关卡片 [[宏就地修改函数语法树]]、[[语法树区分尾表达式]]。
结构图:
classDiagram
class ItemFn {
sig Signature
block Box~Block~
}
class Signature {
output ReturnType
}
class ReturnType {
<<enumeration>>
Default
Type
}
class Block {
stmts Vec~Stmt~
}
class Stmt {
<<enumeration>>
Expr
Macro
}
ItemFn *-- Signature : 函数签名
ItemFn *-- Block : 函数体
Signature *-- ReturnType : 返回类型语法
Block *-- Stmt : 语句列表
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
- · 重写函数的返回值
原书出处 · 1 处
- From panic to result: Error handling 重写函数的返回值 · 查看原书依据
Let’s get back to the task at hand: a macro that replaces panics with results. Let’s do this step by step. First, we will make our function return a Result. For the error type, we will go with a simple String. The value will have to match the current return type of the function. Once we have changed the signature, the final expression—currently returning a Person—will have to be wrapped in an Ok.
参考来源
- 位置:《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#p77)
- 结论依据:7.7 分别处理 ReturnType 与 block.stmts,通过 quote! 和 parse2 生成 Result 返回签名,并将示例尾表达式包装为 Ok。
- 原始内容:Let’s get back to the task at hand: a macro that replaces panics with results. Let’s do this step by step. First, we will make our function return a Result. For the error type, we will go with a simple String. The value will have to match the current return type of the function. Once we have changed the signature, the final expression—currently returning a Person—will have to be wrapped in an Ok.