Rust if...else
In Rust, you can use the if...else
statement to conditionally execute code based on a boolean expression. The basic syntax of an if...else
statement is as follows:
if condition { // code to execute if condition is true } else { // code to execute if condition is false }
Here's an example:
let x = 10; if x > 5 { println!("x is greater than 5"); } else { println!("x is less than or equal to 5"); }
In this example, the if
statement checks whether the value of x
is greater than 5. If it is, the code inside the curly braces after the if
statement is executed, which prints the message "x is greater than 5". If the condition is not true, the code inside the curly braces after the else
statement is executed, which prints the message "x is less than or equal to 5".
You can also chain multiple if
statements together using else if
:
let x = 10; if x > 10 { println!("x is greater than 10"); } else if x == 10 { println!("x is equal to 10"); } else { println!("x is less than 10"); }
In this example, if x
is greater than 10, the first block of code is executed. If x
is equal to 10, the second block of code is executed. Otherwise, the third block of code is executed.
Rust also supports a shorthand syntax for if
statements called the ternary operator. The ternary operator allows you to write a simple if
statement on a single line:
let x = 10; let message = if x > 5 { "greater than 5" } else { "less than or equal to 5" }; println!("x is {}", message);
In this example, the message
variable is assigned either "greater than 5" or "less than or equal to 5" based on the value of x
. The ternary operator is useful for writing simple if
statements that assign a value to a variable.