rust - 移动后使用的价值?
问题描述
我的代码:
fn add(&mut self, key: &str, path: std::path::PathBuf) {
self.key.push(key.to_string());
self.path.push(path);
if key == "img" {
self.img.push(self.create_img(path))
}
}
错误:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/software/init/image.rs:44:27
|
44 | self.img.push(self.create_img(path))
| -------- ---- ^^^^ second mutable borrow occurs here
| | |
| | first borrow later used by call
| first mutable borrow occurs here
error[E0382]: use of moved value: `path`
--> src/software/init/image.rs:44:43
|
40 | fn add(&mut self, key: &str, path: std::path::PathBuf) {
| ---- move occurs because `path` has type `std::path::PathBuf`, which does not implement the `Copy` trait
41 | self.key.push(key.to_string());
42 | self.path.push(path);
| ---- value moved here
43 | if key == "img" {
44 | self.img.push(self.create_img(path))
| ^^^^ value used here after move
解决方案
如果没有其他方法,很难对这段代码进行推理,但是下面的代码应该可以工作(或者至少更接近工作解决方案):
fn add(&mut self, key: &str, path: std::path::PathBuf) {
self.key.push(key.to_string());
// Here, path must be explicitly cloned because of move semantics.
self.path.push(path.clone());
if key == "img" {
// Sometimes compiler cannot determine dependencies of compound
// statement, so with `img` bounding `img` we un-borrow `self`
// (if `create_img` returns owned type). Otherwise you need some
// reference counter like std::rc::Rc.
let img = self.create_img(path);
self.img.push(img);
}
}
推荐阅读
- random - 添加随机效果时出现 bam 错误:数据必须是 data.frame
- android - ViewPager 如何作为 ViewGroup/Container 工作
- r - 在R中找到表格的起始坐标
- python - Numpy - 将矩阵的每个元素与同一位置的另一个矩阵的元素相乘
- python - 如何在 Windows 机器上 pip 安装 Linux 包(对于 AWS Lambda)?
- java - 无法通过 JDBC 禁用 Oracle 外键
- reactjs - 通过 reactjs 上传进度条文件的问题
- regex - Google 死亡测试预期中的匹配行号
- c# - 如何在不添加属性的情况下自定义 Json.net 中嵌套属性的反序列化
- sql - Rails sql内部联接:当只有1行匹配排除条件时,如何排除同一ID上的所有行?