尝试使用相同的资源两次时"使用移动的值"

Sta*_*ich 1 rust borrow-checker

这是代码:

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());
}
Run Code Online (Sandbox Code Playgroud)

如果违规行被注释掉,则代码编译得很好.如果我取消注释它,我开始收到错误:

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
Run Code Online (Sandbox Code Playgroud)

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

我试过玩,&stage_dir但这产生了一些其他警告对我来说更加模糊.

Ste*_*nik 5

TempDir::new给你一个回复Result<TempDir>.你每次试图解开它,而不是打开它一次得到一个TempDir,然后分享.

所以改变

let stage_dir = TempDir::new_in(tmp_dir.as_path(), "Components-Test");
Run Code Online (Sandbox Code Playgroud)

let stage_dir = TempDir::new_in(tmp_dir.as_path(), "Components-Test").unwrap();
Run Code Online (Sandbox Code Playgroud)

代替.

  • 我的意思是,你_could_也分享它,但你不是.你试图解开它两次. (2认同)