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";
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With