Rust has the normal conditions you’d expect with other languages. Similar to go, Rust doesn’t require parenthesis around the boolean condition, unlike many languages.
Rust allows for your standard if - else if - else
style of statements. You can see an example below:
let n = 5;
if n < 0 {
print!("{} is negative", n);
} else if n > 0 {
print!("{} is positive", n);
} else {
print!("{} is zero", n);
}
Changing the value of n
, will change the output you get.
Conditional Statements as an Expression
However, something interesting about Rust, is that a conditional statement, can be used as an expression. That is, you can have a complex condition, and use it to assign a value to a variable. This is unlike most languages where you can only do it through a ternary operator, which means you can only have limited statements.
Consider the following example, and see how you can get more complex statements.
If you do this, then all condition statements must return the same data type.
let age = 18;
let driver_lic = true;
let can_drive =
if driver_lic == true && age >= 16 {
true
}
else {
false
};
Notice that you need a semi-colon at the end of the closing brace, but not in other places, where you are assigning the value. Notice the value is the last one used, no need for a return, or anything like that, and there is no semi-colon there.
Now that you’ve seen a simple version, let’s look at a more complex version of this code:
let age = 13;
let driver_lic = true;
let can_drive =
if age >= 16 {
if driver_lic == true {
true
} else {
println!("You still need a licence to drive, not just be of age.");
false
}
}
else {
println!("You got to be over 16 to even consider driving."); // not having a semi-colon here will generate an error.
false // putting a semi-colon here will generate an error
};
println!("{can_drive}");
Conditions in Rust was originally found on Access 2 Learn
One Comment
Comments are closed.