如何使用Rust检测操作系统类型?

54

如何使用 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";

7
应该使用条件编译吗?”——是的。 - Lukas Kalbertodt
2
根据您需要的默认路径类型,可能已经有一个箱子了,所以您不需要自己编写#[cfg] - kennytm
3个回答

78

虽然有些晚,但是使用std lib内置的方式可以检测操作系统。例如:

use std::env;

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


可能的取值在此处描述。

希望这能对未来的某个人有所帮助。


37

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

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

想要只获取macos,您可以执行以下操作:

if cfg!(target_os = "macos") {
  println!("cargo:rustc-link-lib=framework=CoreFoundation");
}

4
这将Linux、BSD和OSX视为同一平台。有时这是您想要的,但并不总是如此。 - Sean Perry
@SeanPerry 一旦你知道它是一个类UNIX系统,你可以检查文件或命令,以确定你正在运行哪个系统/发行版/版本。 - Federico Razzoli

5

编辑:

自本答案发布以来,似乎os_type创建者撤回了暴露Windows等操作系统的功能。条件编译可能是您最好的选择 - 根据其lib.rsos_type现在似乎只能检测Linux发行版。


原始答案:

您可以始终使用os_type创建。从首页开始:

extern crate os_type;

fn foo() {
      match os_type::current_platform() {
        os_type::OSType::OSX => /*Do something here*/,
        _ => None
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接