create a directory in rust

In order to create a directory in Rust, you can use the standard library's fs module. Specifically, you can use the create_dir function to create a new directory in the specified path.

main.rs
use std::fs::create_dir;

fn main() {
    let path = "/path/to/new/directory";
    match create_dir(path) {
        Ok(_) => println!("Directory created successfully"),
        Err(e) => println!("Error creating directory: {:?}", e),
    }
}
242 chars
10 lines

In this example, we first import the create_dir function from the fs module. Then, we specify the path where we want to create the new directory. Finally, we call create_dir with the specified path.

The create_dir function returns a Result type, so we use a match expression to handle the potential error. If the directory is created successfully, we output a success message. Otherwise, we output an error message with the reason for failure.

Note that in order to create a directory, you need the appropriate permissions on the underlying filesystem. If you try to create a directory in a location where you don't have permissions, the function will return an error.

gistlibby LogSnag