我正在编写一个 Rust 程序,它将根据用户输入创建一个目录。我想知道如何在 error
发生时用我自己的文本 panic
,比如 Permission Error
等等......
fn create_dir(path: &String) -> std::io::Result<()> {
std::fs::create_dir_all(path)?;
Ok(())
}
当发生错误
时,这将不执行任何操作
最佳答案
对于这种情况,最简单的方法是使用 unwrap_or_else()
:
fn create_dir(path: &str) {
std::fs::create_dir_all(path)
.unwrap_or_else(|e| panic!("Error creating dir: {}", e));
}
请注意,出于描述的原因,我还更改了参数类型 here .
但是,接受 &Path
会更符合习惯。或 AsRef<Path>
.
use std::fs;
use std::path::Path;
fn create_dir<P: AsRef<Path>>(path: P) {
fs::create_dir_all(path)
.unwrap_or_else(|e| panic!("Error creating dir: {}", e));
}
关于rust - 无法创建目录时出现 panic ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65573693/