2017-04-08 96 views
2

如何使用Rust检测OS类型?我需要指定一个特定于操作系统的默认路径。应该使用条件编译吗?在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"; 
+6

“*应该使用条件编译吗?*” - 是的。 –

+2

根据你需要什么样的默认路径,可能已经有一个箱子,所以你不需要自己编写'#[cfg]'。 – kennytm

回答

3

编辑:

因为写这个答案,似乎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 
    } 
} 
1

您还可以使用cfg!语法扩展。

if cfg!(windows) { 
    println!("this is windows"); 
} else if cfg!(unix) { 
    println!("this is unix"); 
} 
+0

这将Linux,BSD和OSX视为同一平台。有时候,这是你想要的,但并非总是如此。 –