Rust中的if表达式

if表达式的格式

if 表达式格式:

if 条件表达式 {
    代码段
}

它表示“条件表达式”为 true 时执行“代码段”的内容。下面的代码当输入为偶数时输出“even”:

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");
    }
}

或:

if 条件表达式 {
    代码段1
} else {
    代码段2
}

他表示“条件表达式”为 true 时执行“代码段1”的内容;不成立时执行“代码段2”的内容。下面的代码当输入为偶数时输出“even”,当输入为奇数时输出“odd”:

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");
    }
}

需要注意的是,代码中的条件表达式必须产生一个 bool 类型的值,否则会触发变异错误。与C++或JavaScript等语言不同,Rust不会自动尝试将非布尔类型的值转换为布尔类型。你必须显式地在 if 表达式中提供一个布尔类型作为条件。

使用else if实现多重条件判断

实例程序:

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);
    }
}

在let语句中使用if

示例程序:

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);
}

这里的 res 变量被绑定到了 if 表达式的输出结果上面。当输入的 num 为偶数时 res 将会被赋值为 5,而当 num 不是偶数时 res 将会被赋值为 6。

需要注意的是,if分支与else分支的结果的数据类型应当相同,加入分支表达式产生的类型无法匹配,就会触发编译错误。举个例子:

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);
}

上述代码会导致编译时的错误,因为if与else分支产生了不同类型的值。Rust在错误提示信息中指出了程序出现问题的地方:

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

这段代码中的if表达式会返回一个整数,而else表达式会返回一个字符串。因为变量只能拥有单一的类型,所以这段代码无法通过编译。为了对其它使用 res 变量的代码进行编译时类型检查,Rust需要在编译时确定 res 的具体类型。如果 Rust 能够使用运行时确定的 res 类型,那么它就不得不记录变量所有可能出现的类型,这会使得编译器的实现更加复杂,并丧失许多代码安全保障。

posted @ 2022-01-22 20:56  鱼又悲  阅读(452)  评论(0编辑  收藏  举报