"use of moved value" 尝试使用同一资源两次时

"use of moved value" when trying to use the same resource two times

代码如下:

extern crate tempdir;

use std::env;
use tempdir::*;

#[test]
fn it_installs_component() {
    let current_dir = env::current_dir().unwrap();
    let home_dir = env::home_dir().unwrap();
    let tmp_dir = env::temp_dir();

    println!("The current directory is: {}", current_dir.display());
    println!("The home directory is: {}", home_dir.display());
    println!("The temporary directory is: {}", tmp_dir.display());

    let stage_dir = TempDir::new_in(tmp_dir.as_path(), "Components-Test");

    let components_dir = TempDir::new_in(stage_dir.unwrap().path(), "Components");

    // This is "offending line"
    // let components_make_dir = TempDir::new_in(stage_dir.unwrap().path(), "Components.make");

    println!("---- {:?}", components_dir.unwrap().path());
    //println!("---- {:?}", components_make_dir.unwrap().path());
}

如果有问题的行被注释掉,代码编译正常。如果我取消注释,我会开始收到错误消息:

error[E0382]: use of moved value: `stage_dir`
  --> src/main.rs:21:51
   |
18 |         let components_dir = TempDir::new_in(stage_dir.unwrap().path(), "Components");
   |                                              --------- value moved here
...
21 |         let components_make_dir = TempDir::new_in(stage_dir.unwrap().path(), "Components.make");
   |                                                   ^^^^^^^^^ value used here after move
   |
   = note: move occurs because `stage_dir` has type `std::result::Result<tempdir::TempDir, std::io::Error>`, which does not implement the `Copy` trait

我知道问题是我第一次使用它时移动了 stage_dir,但我看不到如何在这两个子文件夹之间共享 stage_dir,因为我需要在我的测试中访问它们。

我尝试使用 &stage_dir 进行操作,但是这产生了一些其他的警告,这些警告对我来说更加晦涩难懂。

TempDir::new 还给你一个 Result<TempDir>。您尝试每次都打开它,而不是打开它一次以获得 TempDir,然后分享 that.

所以改变

let stage_dir = TempDir::new_in(tmp_dir.as_path(), "Components-Test");

let stage_dir = TempDir::new_in(tmp_dir.as_path(), "Components-Test").unwrap();

相反。