expression

Rust Choose a value with if and else

Use a conditional expression to choose a result rather than assign in both branches. Branch results must agree on a type after applicable coercions. Expected output (not executed): 0 Why: The condition selects the zero-fee branch. Common mistake: Returning an integer from one branch and a string from the other does not automatically convert either.

Formal Syntax & Structure

rust syntaxrust
if condition { value_a } else { value_b }

Working Example

Example Snippetrust
fn main() {    let items = 6;    let fee = if items >= 5 { 0 } else { 3 };    println!("{fee}");}
Rust Reference