Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the path to the home directory for Linux?

Tags:

rust

I need the path contained in $HOME, the path to the home directory. The function home_dir seems to do exactly that but is deprecated. What should I use in its place?

The documentation says this :

Deprecated since 1.29.0: This function's behavior is unexpected and probably not what you want. Consider using a crate from crates.io instead.

What type of crate should I use instead? Is there really no alternative in standard Rust?

like image 211
user2588770 Avatar asked Nov 19 '20 19:11

user2588770


2 Answers

From the home crate.

The definition of home_dir provided by the standard library is incorrect because it relies on the $HOME environment variable which has basically no meaning in Windows. This causes surprising situations where a Rust program will behave differently depending on whether it is run under a Unix emulation environment. Neither Cargo nor rustup use the standard libraries definition - instead they use the definition here.

There is discussion about bringing home_dir back into the standard library, but for now the home crate is probably your best option. It provides canonical definitions of home_dir, cargo_home, and rustup_home:

match home::home_dir() {
    Some(path) => println!("{}", path.display()),
    None => println!("Impossible to get your home dir!"),
}
like image 106
Ibraheem Ahmed Avatar answered Sep 22 '22 12:09

Ibraheem Ahmed


From the dirs crate.

Note that the crate provides paths to many standard directories as defined by operating systems rules, not only the home directory:

Experience has shown that 90% of those asks for $HOME are better served by one of the other functions this crate provides.

If your requirements are more complex, e. g. computing cache, config, etc. paths for specific applications or projects, consider using the directories crate instead.

like image 28
soc Avatar answered Sep 22 '22 12:09

soc