Rust 在for迭代器中调用可变方法的不同方法
我试图在不可变范围内调用一个可变方法,它给了我:Rust 在for迭代器中调用可变方法的不同方法,rust,Rust,我试图在不可变范围内调用一个可变方法,它给了我:error[E0502] 我已经理解了为什么会发生这种错误,但我正在努力解决如何修复它,或者如何使用另一种有效的方法 这是一个麦卡维 struct A { list: Vec<i8>, has_three: bool, } impl A { pub fn new() -> Self { Self { list: vec![1,2,3], h
error[E0502]
我已经理解了为什么会发生这种错误,但我正在努力解决如何修复它,或者如何使用另一种有效的方法
这是一个麦卡维
struct A {
list: Vec<i8>,
has_three: bool,
}
impl A {
pub fn new() -> Self {
Self {
list: vec![1,2,3],
has_three: false,
}
}
pub fn mutable_method(&mut self) {
for item in self.list.iter() {
self.mutable_method2(item);
}
}
fn mutable_method2(&mut self, item: &i8) {
let b: i8 = 3;
if item == &b {
self.has_three = true;
}
}
}
fn main() {
let mut a = A::new();
a.mutable_method();
}
你要求另一种方法。如果我正确地假设你的目标是如果任何条目是3,那么你的目标是让
has\u three
为真,那么这样做就容易多了:
pub fn可变_方法(&mut self){
self.has_three=self.list.iter().any(|&x | x==3);
}
顺便说一句,您需要确保mutable_方法
确实被正确调用,否则您将处于逻辑无效状态。这不是好的做法。考虑已经将此提取到构造函数。
一些背景
潜在的问题是,您最初的方法想要可变地借用self
,而已经不可变地借用了它。然而,从逻辑上讲,您的代码并不明显无效,因为您只是可变地借用了结构的一部分,而不是不变地借用。但是,这些信息丢失了
我们将安全性分解为两个隐式操作
让tmp=self.list.iter().any(|&x | x==3);
self.has_三=tmp;
它们都以“清晰的方式”对结构进行操作,可以是可变的,也可以是不变的。这就是你处理这些问题的方法
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
--> src/main.rs:15:13
|
14 | for item in self.list.iter() {
| ----------------
| |
| immutable borrow occurs here
| immutable borrow later used here
15 | self.mutable_method2(item);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.