我想从循环内的方法获取返回值。但是迭代器也作为可变变量被借用。而且该方法需要一个不变的引用。
这是一个小的可复制代码(playground link):
struct Foo {
numbers: Vec<u8>,
constant: u8
}
impl Foo {
pub fn new()-> Foo {
Foo {
numbers: vec!(1,2,3,4),
constant: 1
}
}
pub fn get_mut(&mut self){
for mut nmb in self.numbers.iter_mut() {
{
let constant = self.get_const();
}
}
}
pub fn get_const(&self)-> u8 {
self.constant
}
}
fn main() {
let mut foo = Foo::new();
foo.get_mut();
}
我收到如下错误:
error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
--> src/main.rs:17:32
|
15 | for nmb in self.numbers.iter_mut() {
| -----------------------
| |
| mutable borrow occurs here
| mutable borrow later used here
16 | {
17 | let constant = self.get_const();
| ^^^^ immutable borrow occurs here
如果self.get_const()
独立于self.numbers
,则可以在循环外进行计算:
let constant = self.get_const();
for mut nmb in self.numbers.iter_mut() {
// ...
}
或直接访问该字段:
for mut nmb in self.numbers.iter_mut() {
let constant = self.constant;
}
如果取决于self.numbers
,则需要使用索引。确保在索引之前计算常数:
for i in 0..self.numbers.len() {
let constant = self.get_const();
let nmb = &mut self.numbers[i];
}
您还需要确保不要插入或删除任何值,因为这可能会导致索引编制错误。