[英]Checking if folder exists in 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();
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())
}
但是,編譯器說我不能在這里移出借用的內容: let x = x.unwrap();
。
自從我ref x
以來,為什么這會移出借用的內容?
模式中的ref
用於構造參考。 如果模式x
類型為T
,則模式ref x
類型為&T
。 但是,移出引用是無效的,因此您絕對不想構造引用! ( unwrap
需要按值進行self
,因此代碼首先嘗試進行移動。)
在這里,閉包上的參數類型是一個引用,因為這就是Iterator::find
想要作為參數傳遞的內容。 如果要解構引用,請改用&
。 但是,如果您在此處編寫模式&x
,您仍然會得到cannot move out of borrowed content
的錯誤,但這一次直接在&x
。
我們該怎么辦呢? DirEntry
沒有實現Clone
,因此我們不能克隆x
(這是&std::io::Result<DirEntry>
)。 相反,我們可以將&Result<DirEntry>
轉換為Result<&DirEntry>
。 標准庫中有一個方法可以做到這一點: as_ref
。
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(|x| {
let x = x.as_ref().unwrap();
x.file_type().unwrap().is_dir() && x.file_name().to_str().unwrap() == "foo"
}).is_some())
}
順便說一句,您可以使用any(...)
而不是執行find(...).is_some()
any(...)
,它更短並且效率可能更高。 any
還將每個迭代值的所有權傳遞給閉包,因此我們實際上不需要將as_ref
與它一起使用!
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())
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.