Getting Started with xdgdir

A step-by-step tutorial to get your app-specific directories like ~/.config/my-app in just a few lines of code.

This tutorial will get you up and running with xdgdir. We’ll write a small program that finds and prints the config and data directories for a fake application called my-app.

Step 1: Add xdgdir to Your Project

First, open your terminal and add xdgdir as a dependency to your Rust project.

Shell
cargo add xdgdir

Step 2: Get the Application Directories

Next, open your src/main.rs file and replace its contents with this code.

Rust
use xdgdir::BaseDir;

fn main() {
    // This gets all the XDG paths for an app named "my-app"
    let dirs = BaseDir::new("my-app").unwrap();

    println!("Config files should go in: {}", dirs.config.display());
    println!("Data files should go in: {}", dirs.data.display());
    println!("Cache files should go in: {}", dirs.cache.display());
}

Here’s what the code does. BaseDir::new("my-app") reads your environment variables to find the correct base paths, then adds /my-app to the end of them.

I’m using .unwrap() here to keep the example simple. The new function returns a Result because it can fail if it can’t find the $HOME directory. In a real application, you should probably handle this error.

Step 3: Run the Code

Now, run the program from your terminal.

Shell
cargo run

You’ll see output that looks something like this, but with your own username.

Plain Text
Config files should go in: /home/your-user/.config/my-app
Data files should go in: /home/your-user/.local/share/my-app
Cache files should go in: /home/your-user/.cache/my-app

And that’s it. The dirs struct contains all the standard XDG paths for your app. You can now use these PathBuf values to read or write your files.

To see all the available paths like state and bin, you can check the Struct definition.