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();
}
}
}
推荐阅读
- html - Bootstrap折叠元素行高问题
- google-cloud-platform - 如何在 GCP Cloud VPN 和我的 PC 之间建立 VPN 隧道?
- laravel - 我正在尝试更新数据,但使用 laravel 时出错
- oracle - Oracle Apex-如何在 LOV 内的选择列表中显示数字范围
- javascript - 如何在类模块外导出变量
- javascript - 在哪里添加用于切换按钮文本的代码?
- apache-flink - FlinkKafkaConsumer 从主题开始读取
- typescript - 重新导出命名的 typescript 接口会引发错误
- sql-server - 如果用户是用户分配托管标识,则确定 Azure SQL Server 中的用户名
- python - 正确使用 XGBRegressor 的增量计算