Rust if in a let
Using "if in a let" statement
The let statement has a ‘if’ expression on its right side, and the ‘let’ statement is given the value of the ‘if’ expression.
Syntax of 'if in a let'
Let variable_name= if condition{
//code blocks
}
else{
//code block
}
The value of the ‘if’ expression is assigned to the variable in the above syntax if the condition is true, and the value of ‘else’ is assigned to the variable if the condition is false.
Example
fn main()
let a=if true
{
1
}
else
{
2
};
println!("value of a is: {}", a);
Output
value of a is: 1
Condition is true in this instance. The value of the ‘if’ statement is the bound for the ‘a’ variable. Currently, a has one value.
Example
fn main()
let b=if false
{
9
}
else
{
"javaTpoint"
};
println!("value of a is: {}", a);
Output
Some errors occurred:E0308
The ‘else’ section in this example evaluates to a string value, but the ‘if’ block evaluates to an integer value. Consequently, because the values in the two blocks are of different types, this program generates an error.