How can one detect the OS type using Rust?

烂漫一生 提交于 2020-06-24 08:26:52

问题


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

回答1:


You can also use cfg! syntax extension.

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



回答2:


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
    }
}



回答3:


It's a little late, but there's a builtin way to detect the OS using the std lib. Eg:

use std::env;

println!("{}", env::consts::OS); // Prints the current OS.


The possible values are described here

Hope this help somebody in the future.



来源:https://stackoverflow.com/questions/43292357/how-can-one-detect-the-os-type-using-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!