rust - 在向迭代器借为可变后,在循环内借为不可变
问题描述
我想从循环内的方法中获取返回值。但迭代器也作为可变对象借用。并且该方法需要一个不可变的引用。
这是一个小的可重现代码(操场链接):
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];
}
您还需要确保不要插入或删除任何值,因为这可能会导致索引错误。
推荐阅读
- python - 如何修复这个基本 Python 程序中没有继续的代码?
- python - Python 程序在使用 ParseFromString 时崩溃
- mysql - 如何在另一个表中有多个主键的情况下创建外键
- linux - 'script' bash 命令挂断在 bash 函数中
- python - Tensorflow:GPU 加速仅在首次运行后发生
- json - 如何只保留键数组中存在的 Postgres jsonb 对象的属性?
- sql - 在 SQL 中,如何删除左侧的前 3 个字符以及特定字符后的右侧的所有字符
- java - 为什么在我只创建单个对象时,下面的代码输出 10 3 次
- node.js - 在没有安装权限的情况下使用服务器上的模块
- php - 如何在浏览器上打印 shell_exec() 错误消息?