知识卡片
临时值借用的延长条件
let r = &factorial(6) 直接把临时计算结果的引用绑定给变量,Rust 会延长这个临时值的作用域,使后续语句可用 r。直接嵌在 let 所初始化的某些构造表达式里的借用也可以延长。书中 r + &1009 只在断言语句内使用该借用。延长取决于写法,若编译器报告临时值先被丢弃,先把结果绑定到作用域合适的具名变量,再借用它。
关联阅读:[[借用有效范围的约束]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- References 临时表达式的借用能用多久 · 查看原书依据
Rust simply creates an anonymous variable to hold the expression’s value and makes the reference point to that.
参考来源
- 位置:《Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)》第04章《References》|临时表达式的借用能用多久,来源项目 `book-source`,`extracted/Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)/_epub-src/OEBPS/ch04.xhtml#borrowing-references-to-arbitrary-expressions`
- 结论依据:原文先解释 Rust 如何为表达式结果安排临时存储,再比较直接初始化与仅在断言中使用的两个例子。
- 原始内容:Rust simply creates an anonymous variable to hold the expression’s value and makes the reference point to that.