If
ifis an expression.All
ifexpressions start with the keywordif, followed by a condition.It’s also worth noting that the condition in this code must be a
bool. If the condition isn’t abool, we’ll get an error.Because
ifis an expression, we can use it on the right side of aletstatement to assign the outcome to a variableReference: Control Flow
if1.rs
fn bigger(a: i32, b: i32) -> i32 {
// fill the function body using if expression
if a > b {
a
} else {
b
}
}
fn main() {
// You can optionally experiment here.
}
// Don't mind this for now :)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ten_is_bigger_than_eight() {
assert_eq!(10, bigger(10, 8));
}
#[test]
fn fortytwo_is_bigger_than_thirtytwo() {
assert_eq!(42, bigger(32, 42));
}
#[test]
fn equal_numbers() {
assert_eq!(42, bigger(42, 42));
}
}This exercise is simple, we just need to add
ifexpression that checks which variable is bigger in the functionbigger.Because
ifis an expression we can just typeaandband it will serve as returned value.
if2.rs
In this example we need to take a look at the predefined testcases.
Test1 -
yummy_food: : expect string"Yummy!"if the argument is"strawberry".Test2 -
neutral_food: expect string"I guess I can eat that."if the argument is"potato".Test3 -
default_disliked_food: expect string"broccoli","gummy bears", or"literally anything".
We are missing two case in the
picky_eaterfunction.So lets add
potatousingelse ifand the rest can go toelseblock.
if3.rs
Because
ifis an expression, we can use it on the right side of aletstatement to assign the outcome to a variableIn this case we just need make sure that the returned values in the
identifierif expression to have the same types.Make
0as substitute of"unknown"value.
Last updated