home_dir, the home directory of the current user in Rust

directories BaseDirs home_dir


fn main() {
    println!("Hello World");

Create a crate

Cleverly (or confusingly ?) call the crate home-dir.

cargo new home-dir
cd home-dir

Add directories crate as a dependency

The directories crate seems to offer what we need here.

cargo add directories

This will update the Cargo.toml file:


name = "home-dir"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

directories = "5.0.1"

Source code


fn main() {
    let bd = directories::BaseDirs::new().unwrap();
    let home_dir = bd.home_dir();

    println!("home_dir: {:?}", home_dir);

Running it:

cargo run

home_dir: "/home/gabor"

Indeed that's my home directory on this computer.

Related Pages

Command line multi-counter with storage in JSON file


Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo