Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Create A Directory In Rust (Recursively)

This is the basic function I use to make directories in Rust. It's like running `mkdir -p /some/path`` on the command line.

Code

use std::path::PathBuf;

fn main() {
    let dir = PathBuf::from("some/path");
    match mkdir_p(dir) {
        Ok(_) => println!("Directory was made or already exists"),
        Err(e) => println!("Error: {}", e)
    }
}

fn mkdir_p(dir: PathBuf) -> std::io::Result<()> {
    if dir.exists() {
        Ok(())
    } else {
        std::fs::create_dir_all(dir)
    }
}

Results

Directory was made or already exists

References