Rust 正在检查目录中是否存在文件夹

Rust 正在检查目录中是否存在文件夹,rust,directory,Rust,Directory,我想知道文件夹foo是否存在于我的当前目录中,因此我编写了一个函数: use std::env; use std::fs; use std::io; fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> { let cur_path_buf = env::current_dir()?; let cur_dir = cur_path_buf.as_path();

我想知道文件夹
foo
是否存在于我的当前目录中,因此我编写了一个函数:

use std::env;
use std::fs;
use std::io;

fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.find(|ref x| {
        let x = x.unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }).is_some())
}
使用std::env;
使用std::fs;
使用std::io;
fn文件夹\u foo\u是否存在于\u current\u目录中()->Result{
设cur_path_buf=env::current_dir()?;
设cur_dir=cur_path_buf.as_path();
Ok(fs::read_dir(cur_dir)?查找(| ref x|{
设x=x.展开();
x、 文件类型()
}).你是某物吗
}
但是,编译器说我不能从这里移出借用的内容:
let x=x.unwrap()


既然I
ref x
,为什么要移出借来的内容?

模式中的
ref
用于构造引用。如果模式
x
将具有类型
T
,则模式
ref x
将具有类型
&T
。但是,移出引用是无效的,因此您肯定不想构造引用!(按值获取
self
,这就是代码首先尝试移动的原因。)

在这里,闭包上的参数类型是引用,因为这是作为参数传递的。如果要解构引用,则需要使用
&
。但是,如果您在这里编写模式
&x
,您仍然会收到错误
无法移出借用的内容
,但这次是直接在
&x

我们能做些什么呢?没有实现
克隆
,因此我们无法克隆
x
(这是一个
&std::io::Result
)。相反,我们可以将
结果
转换为
结果
。标准库中有一个方法可以做到这一点:


没有理由对目录中的所有条目进行迭代以检查是否存在单个条目。只需检查特定项目:

use std::{env, fs, io};

fn does_folder_foo_exist_in_current_directory() -> io::Result<bool> {
    let mut path = env::current_dir()?;
    path.push("foo");
    let metadata = fs::metadata(path)?;
    Ok(metadata.is_dir())
}
使用std:{env,fs,io};
fn文件夹\u foo\u是否存在于\u current\u目录中()->io::Result{
让mut path=env::current_dir()?;
路径推送(“foo”);
让metadata=fs::metadata(路径)?;
Ok(metadata.is_dir())
}
fn does_folder_foo_exist_in_current_directory() -> Result<bool, io::Error> {
    let cur_path_buf = env::current_dir()?;
    let cur_dir = cur_path_buf.as_path();
    Ok(fs::read_dir(cur_dir)?.any(|x| {
        let x = x.unwrap();
        x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
    }))
}
use std::{env, fs, io};

fn does_folder_foo_exist_in_current_directory() -> io::Result<bool> {
    let mut path = env::current_dir()?;
    path.push("foo");
    let metadata = fs::metadata(path)?;
    Ok(metadata.is_dir())
}