知识卡片
扩容会使元素借用失效
向量可能为 push 重新分配内存并搬迁原有元素,仍需使用的旧元素引用会指向被释放的位置。借用检查器禁止在这样一段不可变借用存续期间再可变借用向量。迭代同理:可以借用读取或逐项改写,迭代持有整个向量的借用期间不能插入或删除元素。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 常用集合 Reading Elements of Vectors · 查看原书依据
The code in Listing 8-6 might look like it should work: why should a reference to the first element care about changes at the end of the vector? This error is due to the way vectors work: because vectors put the values next to each other in memory, adding a new element onto the end of the vector might require allocating new memory and copying the old elements to the
参考来源
- 位置:《The Rust Programming Language(第2版)》第08章 常用集合(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c08.xhtml`,块 0041)
- 结论依据:原文把追加末尾与重新分配、旧引用失效联系起来。
- 原始内容:The code in Listing 8-6 might look like it should work: why should a reference to the first element care about changes at the end of the vector? This error is due to the way vectors work: because vectors put the values next to each other in memory, adding a new element onto the end of the vector might require allocating new memory and copying the old elements to the