Path 如何使用Rust检测操作系统类型?
如何使用Rust检测操作系统类型?我需要指定一个特定于操作系统的默认路径。应该使用条件编译吗 例如:Path 如何使用Rust检测操作系统类型?,path,rust,cross-platform,Path,Rust,Cross Platform,如何使用Rust检测操作系统类型?我需要指定一个特定于操作系统的默认路径。应该使用条件编译吗 例如: #[cfg(target_os = "macos")] static DEFAULT_PATH: &str = "path2"; #[cfg(target_os = "linux")] static DEFAULT_PATH: &str = "path0"; #[cfg(target_os = "windows")] static DEFAULT_PATH: &str =
#[cfg(target_os = "macos")]
static DEFAULT_PATH: &str = "path2";
#[cfg(target_os = "linux")]
static DEFAULT_PATH: &str = "path0";
#[cfg(target_os = "windows")]
static DEFAULT_PATH: &str = "path1";
编辑:
自从写下这个答案后,似乎os_type
crater的作者已经收回了暴露Windows等操作系统的功能。条件编译可能是您在这里的最佳选择--os\u type
现在似乎只能检测Linux发行版,从它的特性来看
原始答复: 你可以一直用这个板条箱。首页:
extern crate os_type;
fn foo() {
match os_type::current_platform() {
os_type::OSType::OSX => /*Do something here*/,
_ => None
}
}
您也可以使用
cfg代码>语法扩展
if cfg!(windows) {
println!("this is windows");
} else if cfg!(unix) {
println!("this is unix alike");
}
要获取macos
,您可以执行以下操作:
if-cfg!(target_os=“macos”){
println!(“货物:rustc-link-lib=framework=CoreFoundation”);
}
有点晚了,但是有一种内置的方法可以使用std库检测操作系统。例如:
使用std::env;
普林顿!(“{}”,env::conss::OS);//打印当前操作系统。
描述了可能的值
希望这对将来的人有所帮助。“应该使用条件编译吗?”-是的。根据您需要的默认路径类型,可能已经有一个板条箱,所以您不需要自己编写#[cfg]
。这将Linux、BSD和OSX视为同一个平台。有时这是您想要的,但并非总是如此。@SeanPerry一旦您知道这是一个类似UNIX的系统,您就可以检查文件或命令,这些文件或命令应该告诉您运行的是哪个系统/发行版/版本。