知识卡片

普通读书笔记卡 · 6074.e.2

替换借用值不能留下无效空位

理解等级:中级

&mut T提供独占访问,却不允许随意移出非Copy值并留下无效位置。mem::replace在同一安全操作中放入新值并返回旧值,Option也提供replace便利方法。它维护引用始终指向有效值的约束,不意味着并发原子性或无需外部同步。

这张卡片看不懂?

已有反馈 · 0 条

    还没有人提交反馈。

    在整书笔记中的位置

    原书出处 · 1 处

    • Chapter 3. Concepts Access Control · 查看原书依据

      std::mem::replace function to perform it. Under the covers, replace uses unsafe (as per Item 16) to perform the swap in one go: /// Replace the content of `item` with `val`, returning the previous /// contents. pub fn replace(item: &mut Option<Item>, val: Item) -> Option<Item> { std::mem::replace(item, Some(val)) // returns previous value } For Option types

    参考来源

    - 位置:《Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)》第3章《Access Control》(spine7;extracted/Effective Rust 35 Specific Ways to Improve Your Rust Code (David Drysdale)/_epub-src/OEBPS/ch03.html;u089-ch03-013)。 - 结论依据:原文在“std::mem::replace”附近的定义、例子或代码支撑本卡核心说明:&mut T提供独占访问,却不允许随意移出非Copy值并留下无效位置。边界按已读前提解释;示例未执行。 - 原始内容:std::mem::replace function to perform it. Under the covers, replace uses unsafe (as per Item 16) to perform the swap in one go: /// Replace the content of `item` with `val`, returning the previous /// contents. pub fn replace(item: &mut Option<Item>, val: Item) -> Option<Item> { std::mem::replace(item, Some(val)) // returns previous value } For Option types