我正在编写一个 Rust 程序,它将根据用户输入创建一个目录。我想知道panic
当发生时如何处理我自己的文本error
,比如Permission Error
等等......
fn create_dir(path: &String) -> std::io::Result<()> {
std::fs::create_dir_all(path)?;
Ok(())
}
Run Code Online (Sandbox Code Playgroud)
error
发生此情况时不会执行任何操作
对于这种情况,最简单的方法是使用unwrap_or_else()
:
fn create_dir(path: &str) {
std::fs::create_dir_all(path)
.unwrap_or_else(|e| panic!("Error creating dir: {}", e));
}
Run Code Online (Sandbox Code Playgroud)
请注意,出于此处描述的原因,我还更改了参数类型。
&Path
然而,接受 a或会更惯用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));
}
Run Code Online (Sandbox Code Playgroud)