Open In App

Rust – Configuration Conditional Checks

Last Updated : 22 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Rust uses configurational conditional (cfg) checks to differentiate between the environment that is used to run Rust programs.  This is done by two attributes: 

  • cfg attribute (used in attribute positions)
  • cfg! macro (used in boolean expressions)

The cfg attribute (#cfg) is used when we check attributes in attribute position and enables conditional compilation via non-removal of any codes. On the other hand, the cfg! macro is used when we need to use the value of macros in boolean expressions like evaluation of True or False literals at run time. Whatever expressions are required to be evaluated, cfg! macro do that irrespective of all the conditions.

Example:

Rust




// Rust code for Configuration conditional checks
#[cfg(target_os = "linux")]
fn checking_on_linux() {
    println!("Currently on linux!");
}
  
#[cfg(not(target_os = "linux"))]
fn checking_on_linux() {
    println!("Not on linux!");
}
  
fn main() {
   checking_on_linux();
    if cfg!(target_os = "linux") {
        println!("Running on linux");
    } else {
        println!("Not Running on linux");
    }
}


Output:

 

Explanation:

In this example, we declare a function checking_on_linux() that checks whether the target Operating system is Linux or not. We use the cfg attribute to check whether the Operating system is Linux or not by declaring a target_os variable as “Linux” . Next, we declare and describe another cfg attribute that checks whether the operating system is anything other than Linux or not. After running the code on a terminal-based ide, we can see that the output appended on the screen


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads