我想从循环内部的方法中获取返回值,但是迭代器也被作为可变引用借用了。而方法需要一个不可变引用。
这是一个小的可复现代码 (playground链接):
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
let constant = self.constant;
是否可以? - loganfsmythget_const
返回的值在循环执行期间保持不变,您也可以将其存储在循环外的变量中。 - EvilTaknumbers
向量的当前状态。在此示例中,我仅使用了u8
。在我的用例中,这应该是一个结构体。 - Ramesh Kithsiri HettiArachchinumbers
进行索引,而不是使用迭代器。这样,您可以将可变借用的生命周期缩小到实际更改值的代码部分(playground)。 - Jmb