← 返回起始笔记位置

知识卡片

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

语法树区分尾表达式

理解等级:中级

表达式在 Rust 块末尾遇到分号时,其值会被丢弃。构造返回 Ok(..) 的尾表达式时,书中的 syn 2 写法先用 parse2 取得 Expr,再包成 Stmt::Expr(expr, None),None 对应缺少分号。syn 1 有单独的 Stmt::Semi 和单参数 Stmt::Expr。处理宏语句时也要按版本区分,例如示例的 syn 2 可匹配 Stmt::Macro。

相关卡片 [[改写签名与尾表达式]]。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • From panic to result: Error handling 重写函数的返回值 · 查看原书依据

      As you can see, putting the result back in the block is slightly more complex than retrieving the statement. The simplest way to do it would be to push the parse result. Sadly, that fails with unexpected end of input, expected semicolon. Digging down into the source code, the reason becomes clear: stmts is a vector of Stmt and the Parse implementation of Stmt does not allow statements without a semicolon.

    参考来源

    - 位置:《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#p92) - 结论依据:清单 7.7–7.8 解释为何显式生成 Stmt::Expr 并传 None,并展示 syn 第一、第二主版本的不同定义。 - 原始内容:As you can see, putting the result back in the block is slightly more complex than retrieving the statement. The simplest way to do it would be to push the parse result. Sadly, that fails with unexpected end of input, expected semicolon. Digging down into the source code, the reason becomes clear: stmts is a vector of Stmt and the Parse implementation of Stmt does not allow statements without a semicolon.