Conditional compilation

If you want to make a function that only works on a specific operating system, then annotate it with the #[cfg(target_os = "xyz")] attribute (where xyz can be one of "windows", "macos", "linux", "android", "freebsd", "dragonfly", "bitrig" or "openbsd"). For example, the following code works fine and runs on Windows:

   // from Chapter 3/code/attributes_cfg.rs 
fn main() { 
  on_windows(); 
} 
 
#[cfg(target_os = "windows")] 
fn on_windows() { 
    println!("This machine has Windows as its OS.") 
} 

This produces the following output:

    This machine has Windows as its OS.  

If we try to build this code on a Linux machine, we get the following error:

    error: unresolved name `on_windows  

The code does not even build on Linux, because the attribute prevents it! Furthermore, you can even make your own custom conditions, see http://rustbyexample.com/attribute/cfg/custom.html.

Attributes are also used when testing and benchmarking code.