![](/img/trans.png)
[英]Does Rust's borrow checker really mean that I should re-structure my program?
[英]What is Rust's borrow checker really complaining about here?
考虑对&mut Vec<&mut String>
的简单选择排序:
fn selection_sort(collection: &mut Vec<&mut String>) {
for i in 0..collection.len() {
let mut least_element = i;
for j in (i + 1)..collection.len() {
if collection[j] < collection[least_element] {
least_element = j;
}
}
collection.swap(least_element, i);
}
}
基于这个和那个,这个循环应该可以工作——但是借用会抛出这个错误:
error[E0596]: cannot borrow data in a `&` reference as mutable
--> src/main.rs:58:28
|
58 | if chunks[j] < chunks[least_element] {
| ^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `IndexMut` is required to modify indexed content
或者在较新版本的 Rust 中:
error[E0596]: cannot borrow data in an index of `std::vec::Vec<&mut std::string::String>` as mutable
--> src/lib.rs:5:32
|
5 | if collection[j] < collection[least_element] {
| ^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
|
= help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::vec::Vec<&mut std::string::String>`
让&
引用可变不是更有意义吗?
IndexMut
文档没有使用我理解的示例,并且有一个相当大的示例似乎没有清楚地演示如何使用IndexMut
,尤其是在选择排序或交换元素的上下文中。
错误 0596解释了它在尝试least_element
可变值中借用时发生,但least_element
是可变的。 如果i
更改为mut i
这也可以编译(并且编译器建议从i
删除mut
)。
有 Rustacean 可以照亮这个吗?
当您尝试访问collection[j]
,编译器会返回一个&mut String
因为这是向量元素的类型。 当您尝试访问collection[least_element]
,借用检查器不知道是否least_element != j
,并且具有同一元素的两个可变引用将是未定义的行为。 您可以使用std::ops::Index
返回一个&&mut String
(并且对同一个可变引用有两个不可变引用是安全的),直接借用元素( &collection[j] < &collection[least_element]
)或者,如果可能,将集合类型更改为Vec<&String>
或Vec<String>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.