如何解决基本的借款问题?



我对rust很陌生,我被一个关于借款的非常简单的问题卡住了。我将代码简化如下:

pub struct MyStruct {
pub val: i32
}
impl MyStruct {
pub fn new(val: i32) -> Self {
MyStruct {
val
}
}
}
pub struct MyStructVec {
pub vec: Vec::<MyStruct>
}
impl MyStructVec {
pub fn new() -> Self {
MyStructVec {
vec: Vec::new()
}
}
pub fn insert(&mut self, mut my_struct: MyStruct) {
self.vec.push(my_struct);
}
fn run(&mut self) {
for s in self.vec.iter_mut() {
s.val = s.val + 1;
self.edit(s);
}
}
fn edit(&self, my_struct: &mut MyStruct) {
my_struct.val = my_struct.val * 2;
}
}
fn main() {
let mut my_struct1 = MyStruct::new(69);
let mut my_struct2 = MyStruct::new(420);
let mut my_struct_vec = MyStructVec::new();
my_struct_vec.insert(my_struct1);
my_struct_vec.insert(my_struct2);
my_struct_vec.run();
}

当我运行这个时,我得到以下错误:

error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
--> src/main.rs:33:13
|
31 |         for s in self.vec.iter_mut() {
|                  -------------------
|                  |
|                  mutable borrow occurs here
|                  mutable borrow later used here
32 |             s.val = s.val + 1;
33 |             self.edit(s);
|             ^^^^ immutable borrow occurs here

但是如果我像这样编辑代码:

fn run(&mut self) {
for s in self.vec.iter_mut() {
s.val = s.val + 1;
//self.edit(s);
s.val = s.val * 2;
}
}

那么它运行得很好。这个例子是一个简化的情况,但在我的实际代码中,我可能只是想把我的代码分离到一个单独的函数中,以更容易阅读,就像编辑函数一样。那么在Rust中正确的方法是什么呢?非常感谢!

我认为错误是由于某种原因,你正在使你的MyStructVec修改MyStruct,当它可以是简单的MyStruct方法。你的参考资料比你需要的还要多,而且你并没有真正拿到你需要的。似乎公平的是,edit应该封装在要修改的对象中:


impl MyStruct {
...

fn edit(&mut self) {
self.val = self.val * 2;
}
}
...
impl MyStructVec {
...
fn run(&mut self) {
for s in self.vec.iter_mut() {
s.val = s.val + 1;
s.edit();
}
}
}

游乐场

最新更新