Attributes
In the compiler, you may have already seen examples of warnings between #[ ... ]
signs, like #[warn(unused_variables)]
. These are attributes which represent metadata information about the code. You can use these yourself in code, and they are placed right before an item (such as a function) on which they have something to say. They can, for example, disable certain classes of warnings, turn on certain compiler features, or mark functions as being part of unit tests or benchmark code.
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...