How can one detect the OS type using Rust?

2020-06-03 02:04发布

How can one detect the OS type using Rust? I need to specify a default path specific to the OS. Should one use conditional compilation?

For example:

#[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";

2条回答
Fickle 薄情
2楼-- · 2020-06-03 02:30

EDIT:

Since writing this answer, it seems the author of the os_type crate has retracted functionality that exposed OSes like Windows. Conditional compilation is probably your best bet here -- os_type only seems to detect Linux distributions now, judging from its lib.rs.


ORIGINAL ANSWER:

You could always use the os_type crate. From the front page:

extern crate os_type;

fn foo() {
      match os_type::current_platform() {
        os_type::OSType::OSX => /*Do something here*/,
        _ => None
    }
}
查看更多
Rolldiameter
3楼-- · 2020-06-03 02:42

You can also use cfg! syntax extension.

if cfg!(windows) {
    println!("this is windows");
} else if cfg!(unix) {
    println!("this is unix alike");
}
查看更多
登录 后发表回答