Rust's conditional compilation allows selectively including or excluding code during compilation based on different conditions (such as target platform, feature flags, etc.). Mainly implemented through the #[cfg]
attribute and cfg!
macro.
1. #[cfg(...)] Attribute
Different functions will be compiled for different operating systems, with non-matching code being completely removed:
#[cfg(target_os = "linux")]
fn get_os_info(){
println!("linux");
}
#[cfg(target_os = "windows")]
fn get_os_info() {
println!("windows");
}
fn main() {
get_os_info();
}
You can add combined conditions:
all()
means all conditions must be met.any()
means any one condition being met is sufficient.not()
means condition negation.
#[cfg(not(target_os = "linux"))]
fn get_os_info() {
println!("not linux");
}
This function will be compiled on non-Linux systems.
2. cfg! Macro
The cfg!
macro evaluates conditions during compilation and returns a bool
value:
fn main() {
if cfg!(target_os = "linux") {
println!("linux");
} else {
println!("not linux");
}
}
Which method to use depends on the specific situation.