首页 > 解决方案 > 如何解决基本借款问题?

问题描述

我对生锈还很陌生,我被困在一个关于借贷的可能非常简单的问题上。我已将代码简化为如下:

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 中执行此操作的正确方法是什么?非常感谢!

标签: rust

解决方案


我认为错误在于,由于某种原因,当它可能是简单的方法时,您正在进行MyStructVec修改。您正在处理您需要的更多参考资料,而您并没有真正获取您需要的参考资料。应该将其封装在要修改的对象中似乎是公平的:MyStructMyStructedit


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();
        }
    }
}

操场


推荐阅读