知识卡片
取出元素时保持集合有效
索引 Vec 时,移动元素会留下一个集合无法表示的空槽。只查看用 &v[i],拿走末尾用 pop,把次序改变换成直接补洞用 swap_remove,在原位置填入替代值用 std::mem::replace。若要逐个取得全部元素的所有权,for item in v 可以一次接手整个向量,再依次交出元素。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Ownership and Moves 保持集合有效地取得元素所有权 · 查看原书依据
Each one of these methods moves an element out of the vector, but does so in a way that leaves the vector in a state that is fully populated
参考来源
- 位置:《Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)》第03章《Ownership and Moves》|保持集合有效地取得元素所有权,来源项目 `book-source`,`extracted/Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)/_epub-src/OEBPS/ch03.xhtml#moves-and-indexed-content`
- 结论依据:原文展示索引移动的编译错误、三种保持槽位有效的取值方法,以及消费整只向量的循环。
- 原始内容:Each one of these methods moves an element out of the vector, but does so in a way that leaves the vector in a state that is fully populated