[英]rust - how to resolve basic borrow issues?
我对 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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.