if expression in Rust

Posted by angelkay73 on Wed, 26 Jan 2022 07:14:33 +0100

Format of if expression

if expression format:

if Conditional expression {
    Code snippet
}

It represents the content of the code snippet executed when the conditional expression is true. The following code outputs "even" when the input is an even number:

use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let num: i32 = s.trim().parse().unwrap();
    if num % 2 == 0 {
        println!("even");
    }
}

Or:

if Conditional expression {
    Code snippet 1
} else {
    Code snippet 2
}

It means to execute the content of "code segment 1" when "conditional expression" is true; Execute the contents of "code snippet 2" when it is not true. The following code outputs "even" when the input is an even number and "odd" when the input is an odd number:

use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let num: i32 = s.trim().parse().unwrap();
    if num % 2 == 0 {
        println!("even");
    } else {
        println!("odd");
    }
}

It should be noted that the conditional expression in the code must produce a value of bool type, otherwise a mutation error will be triggered. Unlike languages such as C + + or JavaScript, Rust does not automatically attempt to convert non Boolean values to Boolean types. You must explicitly provide a boolean type as a condition in the if expression.

Multiple conditional judgment using else if

Instance program:

use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let num: i32 = s.trim().parse().unwrap();
    if num % 5 == 0 {
        println!("{} is divisible by 5.", num);
    } else if num % 3 == 0 {
        println!("{} is divisible by 3.", num);
    } else if num % 2 == 0 {
        println!("{} is divisible by 2.", num);
    } else {
        println!("{} is not divisible by 5, 3, or 2.", num);
    }
}

Using if in a let statement

Sample program:

use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let num: i32 = s.trim().parse().unwrap();
    let res = if num % 2 == 0 {
        5
    } else {
        6
    };
    println!("res = {}", res);
}

The res variable here is bound to the output of the if expression. When the input num is even, res will be assigned 5, and when num is not even, res will be assigned 6.

It should be noted that the data types of the results of the if branch and the else branch should be the same. If the types generated by adding the branch expression cannot match, a compilation error will be triggered. for instance:

use std::io;

fn main() {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let num: i32 = s.trim().parse().unwrap();
    let res = if num % 2 == 0 {
        123
    } else {
        "yuyoubei"
    };
    println!("res = {}", res);
}

The above code will cause compile time errors because the if and else branches produce different types of values. Rust pointed out the problems in the program in the error message:

error[E0308]: `if` and `else` have incompatible types
  --> src\main.rs:10:9
   |
7  |       let res = if num % 2 == 0 {
   |  _______________-
8  | |         123
   | |         --- expected because of this
9  | |     } else {
10 | |         "yuyoubei"
   | |         ^^^^^^^^^^ expected integer, found `&str`
11 | |     };
   | |_____- `if` and `else` have incompatible types

The if expression in this code will return an integer, while the else expression will return a string. Because variables can only have a single type, this code cannot be compiled. In order to perform compile time type checking on other codes that use res variables, Rust needs to determine the specific type of res at compile time. If Rust can use the res type determined at runtime, it will have to record all possible types of variables, which will make the implementation of the compiler more complex and lose many code security guarantees.