简体   繁体   English

如何找到 Linux 主目录的路径?

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

I need the path contained in $HOME , the path to the home directory.我需要$HOME包含的路径,即主目录的路径。 The function home_dir seems to do exactly that but is deprecated.函数home_dir似乎正是这样做的,但已被弃用。 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. 1.29.0 后已弃用:此函数的行为是意外的,可能不是您想要的。 Consider using a crate from crates.io instead.考虑使用 crates.io 中的 crate。

What type of crate should I use instead?我应该使用什么类型的板条箱? Is there really no alternative in standard Rust?标准 Rust 真的没有替代品吗?

From the home crate.home箱子里。

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.标准库提供的home_dir定义是错误的,因为它依赖于$HOME环境变量,在 Windows 中基本没有意义。 This causes surprising situations where a Rust program will behave differently depending on whether it is run under a Unix emulation environment.这会导致令人惊讶的情况,其中 Rust 程序会根据它是否在 Unix 仿真环境下运行而表现不同。 Neither Cargo nor rustup use the standard libraries definition - instead they use the definition here. Cargo 和 rustup 都不使用标准库定义——而是使用这里的定义。

There is discussion about bringing home_dir back into the standard library, but for now the home crate is probably your best option.讨论关于把home_dir回标准库,但对于现在的home箱子可能是你最好的选择。 It provides canonical definitions of home_dir , cargo_home , and rustup_home :它提供了home_dircargo_homerustup_home规范定义:

match home::home_dir() {
    Some(path) => println!("{}", path.display()),
    None => println!("Impossible to get your home dir!"),
}

From the dirs crate.来自dirs板条箱。

Note that the crate provides paths to many standard directories as defined by operating systems rules, not only the home directory, because experience has shown that 90% of those asks for $HOME are better served by one of the other functions this crate provides.请注意,crate 提供了操作系统规则定义的许多标准目录的路径,而不仅仅是主目录,因为经验表明,90% 的请求$HOME可以通过该 crate 提供的其他功能之一更好地提供服务。

If your requirements are more complex, eg computing cache, config, etc. paths for specific applications or projects, consider using the directories crate instead.如果您的要求更复杂,例如计算特定应用程序或项目的缓存、配置等路径,请考虑使用目录crate。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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