2

I'm writing a Rust program which will create a directory based on user input. I would like to know how to panic with my own text when error occurs, like Permission Error etc...

fn create_dir(path: &String) -> std::io::Result<()> {
    std::fs::create_dir_all(path)?;
    Ok(())
}

This will do nothing when error occcurs

vallentin
  • 23,478
  • 6
  • 59
  • 81
Marcel Kopera
  • 304
  • 2
  • 9

1 Answers1

5

For this case, the simplest way is to use unwrap_or_else():

fn create_dir(path: &str) {
    std::fs::create_dir_all(path)
        .unwrap_or_else(|e| panic!("Error creating dir: {}", e));
}

Note that I also changed the argument type, for the reasons described here.


However, it would be more idiomatic to accept a &Path or 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));
}
vallentin
  • 23,478
  • 6
  • 59
  • 81
Cerberus
  • 8,879
  • 1
  • 25
  • 40
  • 1
    It is probably because you have the permisions to create a directory. Try and example like - ```std::fs::create_dir_all("/some/dir/") .unwrap_or_else(|e| panic!("Error creating dir: {}", e));``` in the rust playground and it fails with a permission denied eror. – Cool Developer Jan 05 '21 at 05:39
  • thanks for the answer, this worked! May I ask you, what that `|e| ` means? – Marcel Kopera Jan 05 '21 at 05:40
  • 2
    @MarcelKopera `|e| panic!("Error creating dir: {}", e)` is a closure, where `e` is the error value. Thereby if `create_dir_all()` returns an `Err` then the closure is called resulting in the `panic!` – vallentin Jan 05 '21 at 05:42