知识卡片
临时值借用需要足够存活期
表达式中创建的临时值可能在语句结束时释放,若函数返回借自它的引用并在以后使用,就会被拒绝。把拥有值先绑定到变量可给出清楚的存活范围。临时值延长与提升另有具体规则,不能把“所有临时值都在分号处销毁”当作无例外定律。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 3. Concepts Scope of a Lifetime · 查看原书依据
temporary value dropped while borrowed --> src/main.rs:209:46 | 209 | let r: &Item = fn_returning_ref(&mut Item { contents: 42 }); | ^^^^^^^^^^^^^^^^^^^^^ - temporary | | value is freed at the | | end of this statement | | | creates a temporary value which is | freed while still in use 210 | println!("r.contents = {}", r.contents); | ---------- borrow later
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第3章《Scope of a Lifetime》(spine7;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch03.html;u080-ch03-003)。
- 结论依据:原文在“temporary value dropped while borrowed”附近的定义、例子或代码支撑本卡核心说明:表达式中创建的临时值可能在语句结束时释放,若函数返回借自它的引用并在以后使用,就会被拒绝。边界按已读前提解释;示例未执行。
- 原始内容:temporary value dropped while borrowed --> src/main.rs:209:46 | 209 | let r: &Item = fn_returning_ref(&mut Item { contents: 42 }); | ^^^^^^^^^^^^^^^^^^^^^ - temporary | | value is freed at the | | end of this statement | | | creates a temporary value which is | freed while still in use 210 | println!("r.contents = {}", r.contents); | ---------- borrow later