Last active
November 12, 2022 03:10
-
-
Save Caellian/eae57174d6b3e931fe59d1259b82d7e3 to your computer and use it in GitHub Desktop.
Rust match target_os macro
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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