rust - 无法创建目录时出现 panic

标签 rust

我正在编写一个 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/

相关文章:

rust - 从 Vec<proc() -> uint> 调用过程

rust - 如何编写知道实现者是 [u8] 的特征方法?

rust - 如何使用 yewdux 消除 use_store 的编译器错误?

macros - 是否可以使用 Rust 宏以程序方式声明变量?

rust - 为什么 `cargo build` 不显示我代码中的所有错误?

rust - Rust 中的冒号运算符与 C 中的冒号运算符有何相似之处?

rust - 如何分配切片范围? [复制]

rust - 从函数返回 future 值

rust - 创建一个简单的链表

rust - 将 Arc<Future> 移动到线程池中