gpt4 book ai didi

rust - 借用为迭代器可变后,在循环内借用为不可变

转载 作者:行者123 更新时间:2023-12-03 11:30:55 27 4
gpt4 key购买 nike

我想从循环内的方法获取返回值。但是迭代器也被借用为可变的。并且该方法需要一个不可变的引用。

这是一个小的可重现代码(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];
}

您还需要确保不要插入或删除任何值,因为这可能会导致索引错误。

关于rust - 借用为迭代器可变后,在循环内借用为不可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62203326/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com