首页 > 解决方案 > 移动后使用的价值?

问题描述

我的代码:

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

标签: rust

解决方案


如果没有其他方法,很难对这段代码进行推理,但是下面的代码应该可以工作(或者至少更接近工作解决方案):

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

推荐阅读