Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one detect the OS type using Rust?

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";
like image 881
Constantine Avatar asked Apr 08 '17 09:04

Constantine


2 Answers

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.

like image 170
Fausto Alonso Avatar answered Nov 20 '22 05:11

Fausto Alonso


You can also use cfg! syntax extension.

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

To just get macos, you can do:

if cfg!(target_os = "macos") {
  println!("cargo:rustc-link-lib=framework=CoreFoundation");
}
like image 33
Bo Lu Avatar answered Nov 20 '22 06:11

Bo Lu