Rust if expression
Created By: chatGPT
Rust provides the powerful
if
expression to handle conditional logic in your programs. Unlike traditional imperative languages, Rust treats if
as an expression, meaning that it can return a value. This feature allows for more concise and expressive code. Here's a basic example illustrating how the if
expression works:let number = 6;
let result = if number % 2 == 0 {
"Even"
} else {
"Odd"
};
println!("The number is {}.", result);
In this code snippet, we declare a variable
number
and then use an if
expression to determine if it is even or odd. Depending on the condition, it assigns either "Even" or "Odd" to the variable result
. Finally, we use println!
to display the result.let number = 9;
let result = if number > 0 {
"Positive"
} else if number < 0 {
"Negative"
} else {
"Zero"
};
println!("The number is {}.", result);
You can also chain multiple conditions using
Moreover, else if
. In this example, we check if a number is positive, negative, or zero. The if
expression here evaluates the first true condition and assigns the corresponding value to result
.let a = 20;
let b = 30;
let max = if a > b {
a
} else {
b
};
println!("The maximum number is {}.", max);
if
expressions can return values of different types, as long as they are of the same type. In this case, we evaluate which of two numbers, a
or b
, is larger, and we store that value in the variable max
. This shows the versatility and power of if
expressions in Rust.