Create A Directory In Rust If It Doesn't Already Exist

rust

use std::fs;
use std::path::PathBuf;

fn main() {
    let path = PathBuf::from("verify-exists/sub-path");
    match verify_dir(&path) {
        Ok(()) => println!("Verified the directory exists"),
        Err(e) => println!("{}", e)
    }
}

fn verify_dir(dir: &PathBuf) -> std::io::Result<()> {
    if dir.exists() {
        Ok(()) 
    } else {
        fs::create_dir_all(dir)
    }
}
            
Verified the directory exists
        

This is the function I use to make sure a directory exists before trying to do something with it. If the target directory doesn't exist, it'll be made recursively. If it can't be made for some reason it'll throw an error. Note that just because the directory exists doesn't mean the permissions are writeable.