Skip to content

Instantly share code, notes, and snippets.

@Caellian
Last active November 12, 2022 03:10
Show Gist options
  • Save Caellian/eae57174d6b3e931fe59d1259b82d7e3 to your computer and use it in GitHub Desktop.
Save Caellian/eae57174d6b3e931fe59d1259b82d7e3 to your computer and use it in GitHub Desktop.
Rust match target_os macro
/// Match target_os compile time constant.
///
/// Usage:
/// ```
/// match_os! {
/// "windows" => println!("hello from windows"),
/// "linux" | "macos" => {
/// println!("hello from unix")
/// },
/// _ => {
/// println!("hello from unhandled")
/// }
/// }
/// ```
///
/// Non exaustive match will cause compiler error when compiling for unhandled target_os.
///
#[macro_export]
macro_rules! match_os {
{$($($sys: literal)|+ => $v: expr),+ , _ => $otherwise: expr } => {
$(
#[cfg(any($(target_os = $sys),+))]
$v
)+
#[cfg(not(any($($(target_os = $sys),+),+)))]
$otherwise
};
{$($($sys: literal)|+ => $v: expr),+} => {
match_os!{
$($($sys)|+ => $v),+ , _ => { compile_error!("current system not handled"); }
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment