Getting Global Base Directories

Sometimes you just need the raw base paths, not the app-specific ones. This guide shows you how to do that.

The BaseDir::new() function is great for getting paths for your own app, but sometimes you need the raw, base directories themselves, like ~/.config or ~/.local/share.

This guide shows you how to get those global paths without an application name added to the end.

Getting the Global Dirs

To get the base directories, you can use the BaseDir::global() function. It works just like BaseDir::new() but it skips the step of adding your app’s name.

Here’s an example.

Rust
use xdgdir::BaseDir;

fn main() {
    // Get the global, non-app-specific directories
    let global_dirs = BaseDir::global().unwrap();

    println!("Global config dir: {}", global_dirs.config.display());
    println!("Global data dir: {}", global_dirs.data.display());
    println!("User executables dir: {}", global_dirs.bin.display());
}

How it Works

The BaseDir::global() function does the same work of checking environment variables and falling back to defaults, but it stops there. It gives you the raw PathBuf for each base directory.

In fact, BaseDir::new("my-app") is just a simple wrapper around BaseDir::global() that adds the app name for you.

When you run the code above, you’ll get something like this.

Plain Text
Global config dir: /home/your-user/.config
Global data dir: /home/your-user/.local/share
User executables dir: /home/your-user/.local/bin

When to Use This

You’ll want to use BaseDir::global() if you’re building a tool that works with the directory structure itself. For example, you might need it if you’re writing a script to list the contents of the user’s config directory, or if you need to manually build a path that doesn’t fit the standard .../my-app pattern.

The BaseDir struct you get back has all the same fields, just without the final path component.