Conditional Rust Function Compilation

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we have a code snippet that includes a function called conditional_function(), but it will only be compiled and executed if a custom conditional called some_condition is passed to rustc using the --cfg flag.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") subgraph Lab Skills rust/function_syntax -.-> lab-99343{{"`Conditional Rust Function Compilation`"}} rust/expressions_statements -.-> lab-99343{{"`Conditional Rust Function Compilation`"}} end

Custom

Some conditionals like target_os are implicitly provided by rustc, but custom conditionals must be passed to rustc using the --cfg flag.

#[cfg(some_condition)]
fn conditional_function() {
    println!("condition met!");
}

fn main() {
    conditional_function();
}

Try to run this to see what happens without the custom cfg flag.

With the custom cfg flag:

$ rustc --cfg some_condition custom.rs && ./custom
condition met!

Summary

Congratulations! You have completed the Custom lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like