1

这是代码:

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但这产生了一些对我来说更加模糊的警告。

4

1 回答 1

5

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

所以改变

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

反而。

于 2015-12-30T15:57:57.277 回答