Con*_*ine 9 cross-platform path rust
如何使用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 = "path1";
Run Code Online (Sandbox Code Playgroud)
小智 24
有点晚了,但是有一种内置的方法可以使用 std lib 检测操作系统。例如:
use std::env;
println!("{}", env::consts::OS); // Prints the current OS.
Run Code Online (Sandbox Code Playgroud)
希望这对将来的人有所帮助。
编辑:
自从写完这个答案后,该包的作者似乎os_type已经撤回了暴露 Windows 等操作系统的功能。条件编译可能是你最好的选择——os_type从lib.rs来看,现在似乎只能检测 Linux 发行版。
原答案:
你可以随时使用这个os_type板条箱。从首页:
extern crate os_type;
fn foo() {
match os_type::current_platform() {
os_type::OSType::OSX => /*Do something here*/,
_ => None
}
}
Run Code Online (Sandbox Code Playgroud)
您也可以使用cfg!语法扩展。
if cfg!(windows) {
println!("this is windows");
} else if cfg!(unix) {
println!("this is unix alike");
}
Run Code Online (Sandbox Code Playgroud)