Rust &引用;“移动值”的使用;尝试两次使用同一资源时
代码如下:Rust &引用;“移动值”的使用;尝试两次使用同一资源时,rust,borrow-checker,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 cur
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]:使用移动值:`stage\u dir`
-->src/main.rs:21:51
|
18 | let components_dir=TempDir::new_in(stage_dir.unwrap().path(),“components”);
|------值移到了这里
...
21 |让组件_make_dir=TempDir::new_进入(stage_dir.unwrap().path(),“components.make”);
|^^^^^^^^^^^移动后此处使用的值
|
=注意:发生移动是因为'stage_dir'的类型为'std::result::result',而该类型不实现'Copy'特性
我知道问题是我第一次使用时移动了stage\u dir
,但我看不到如何在这两个子文件夹之间共享stage\u dir
,因为我需要在测试中访问这两个子文件夹
我试着玩了
&stage\u dir
,但这产生了一些对我来说更加模糊的警告。TempDir::new
返回了一个结果。您每次都尝试将其展开,而不是将其展开一次以获得一个TempDir
,然后将其共享
所以改变
let stage_dir = TempDir::new_in(tmp_dir.as_path(), "Components-Test");
到
相反。TempDir::new
返回一个结果
。您每次都尝试将其展开,而不是将其展开一次以获得一个TempDir
,然后将其共享
所以改变
let stage_dir = TempDir::new_in(tmp_dir.as_path(), "Components-Test");
到
相反。谢谢您的及时回答,现在它可以工作了!我仍然不明白为什么不打开的物品不能被共享,反之亦然-是否有指向某个地方的链接或简单的解释?我的意思是,你也可以共享它,但你没有。您试图打开它两次。感谢您的及时回答,现在它正在工作!我仍然不明白为什么不打开的物品不能被共享,反之亦然-是否有指向某个地方的链接或简单的解释?我的意思是,你也可以共享它,但你没有。你想把它拆开两次。