知识卡片
内部引用不能活过借用守卫
RefCell::borrow返回Ref守卫,其存活维持动态借用。若在map闭包内取出&Item再返回,闭包结束时守卫已释放,内部引用就失去对应保障。应把守卫保留到使用完成,例如在match分支里调用check_item;仅让Rc继续存活不能替代守卫。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Chapter 3. Concepts Local code refactoring · 查看原书依据
Option<std::cell::Ref<Item>> = x1.map(|r| r.borrow()); let x3: Option<&Item> = x2.map(|r| r.deref()); check_item(x3); error[E0515]: cannot return reference to function parameter `r` --> src/main.rs:305:40 | 305 | let x3: Option<&Item> = x2.map(|r| r.deref()); | ^^^^^^^^^ returns a reference to | data owned by the current function This narrows down the precis
参考来源
- 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第3章《Local code refactoring》(spine7;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch03.html;u093-ch03-017)。
- 结论依据:原文在“Option<std::cell::Ref<Item>>”附近的定义、例子或代码支撑本卡核心说明:RefCell::borrow返回Ref守卫,其存活维持动态借用。边界按已读前提解释;示例未执行。
- 原始内容:Option<std::cell::Ref<Item>> = x1.map(|r| r.borrow()); let x3: Option<&Item> = x2.map(|r| r.deref()); check_item(x3); error[E0515]: cannot return reference to function parameter `r` --> src/main.rs:305:40 | 305 | let x3: Option<&Item> = x2.map(|r| r.deref()); | ^^^^^^^^^ returns a reference to | data owned by the current function This narrows down the precis