delete a directory in rust

To delete a directory in Rust, you can use the std::fs::remove_dir function. It takes a path to the directory as an argument and returns a Result<(), std::io::Error>.

main.rs
use std::fs;

fn main() -> std::io::Result<()> {
    // delete directory named "my_dir"
    fs::remove_dir("my_dir")?;
    Ok(())
}
132 chars
8 lines

Note that the function will fail if the directory is not empty. To recursively delete a directory and all its content, you can use the std::fs::remove_dir_all function:

main.rs
use std::fs;

fn main() -> std::io::Result<()> {
    // delete directory named "my_dir" and all its content
    fs::remove_dir_all("my_dir")?;
    Ok(())
}
156 chars
8 lines

Both functions return an std::io::Error if something goes wrong during the deletion, so it's important to handle the result properly.

gistlibby LogSnag