Getting Application-Specific Directories
The most common use case. How to get the config, data, and cache paths for your app.
Most of the time, you’ll use xdgdir
to find the correct paths for your own
application. Instead of just getting a base path like ~/.config
, you need a
special place for your app, like ~/.config/my-app
.
This guide shows you the main function for doing exactly that.
Getting the Paths
The main function you’ll need is BaseDir::new()
. You give it your
application’s name as a string, and it returns a BaseDir
struct with all the
paths correctly set up for you.
Here’s how you use it.
use xdgdir::BaseDir;
fn main() {
// Get the XDG paths for an app called "my-app"
let dirs = BaseDir::new("my-app").unwrap();
println!("Config: {}", dirs.config.display());
println!("Data: {}", dirs.data.display());
println!("Cache: {}", dirs.cache.display());
}
How it Works
The BaseDir::new()
function does two things.
- It first resolves the global base directories by checking environment variables and using defaults.
- Then, it appends your application name to the end of the relevant paths.
When you run the code, you’ll get output like this.
Config: /home/your-user/.config/my-app
Data: /home/your-user/.local/share/my-app
Cache: /home/your-user/.cache/my-app
The paths that get your app’s name added are: config
, data
, cache
,
state
, and runtime
(if it exists).
The home
and bin
paths are not changed because they are global and not meant
to be specific to one app.
The BaseDir::new()
function returns a Result
, which means it can fail. I’m
using .unwrap()
here to keep it simple, but you should handle this in a real
application. For a full guide on that, check out the
Error Handling guide.