简体   繁体   中英

Where should I save my config files in Rust

I need to persist information, such as the user's configuration for my program and their input. Where would the best place be to save this files on Linux and Windows?

This is for a rust-cargo program, which will be installed into ~/.cargo/bin for its usage. I have tried to save my files into ~/.cargo but I don't know if this is appropiate, as I am new into Rust .

There's nothing special for applications written in Rust. Contrary to other solutions coming with a runtime, Rust builds normal applications relying on the standard env and practices. The normal rules of the system apply for configuration locations.

On linux you should first query the XDG paths then use $HOME as fallback when it's not available.

Here's how you can do it:

use std::env::var;

fn main() {
    let config_home = var("XDG_CONFIG_HOME")
        .or_else(|_| var("HOME").map(|home|format!("{}/.config", home)));
    println!("{:?}", config_home);
}

Note that several libraries do this job for you and take care of supporting alternate operating systems.

I won't link to them because they are many of them and they often change but your favourite search engine will direct you to the most popular ones if you search for "rust configuration directory".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM