知识卡片

普通读书笔记卡 · 6074.d.1.a.3.c.6

宏可补位置同时保留原结果

理解等级:中级

诊断宏可先对表达式求值一次,失败时输出file!、line!与stringify!信息,再把原Result返回。这样调用者仍决定是否传播或恢复,日志不会悄悄替它终止流程。应留意错误值可能含敏感内容,表达式文本也不应当成稳定机器协议。

这张卡片看不懂?

已有反馈 · 0 / 10 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 5. Tooling When to Use Macros · 查看原书依据

      log_failure { { $e:expr } => { { let result = $e; if let Err(err) = &result { eprintln!("{}:{}: operation '{}' failed: {:?}", file!(), line!(), stringify!($e), err); } result } } } When failures occur, the log file then automatically includes details of what failed and where: use std::convert::TryInto; let x: Result<u8, _> = log_failure!(512.try_into()); //

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第5章《When to Use Macros》(spine9;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch05.html;u147-ch05-018)。 - 结论依据:原文在“log_failure”附近的定义、例子或代码支撑本卡核心说明:诊断宏可先对表达式求值一次,失败时输出file!、line!与stringify!信息,再把原Result返回。边界按已读前提解释;示例未执行。 - 原始内容:log_failure { { $e:expr } => { { let result = $e; if let Err(err) = &result { eprintln!("{}:{}: operation '{}' failed: {:?}", file!(), line!(), stringify!($e), err); } result } } } When failures occur, the log file then automatically includes details of what failed and where: use std::convert::TryInto; let x: Result<u8, _> = log_failure!(512.try_into()); //