Rust 条件语句


Rust 条件语句

条件语句是编程中常用的控制流语句,可以根据判断条件的成立与否来执行不同的代码块。在 Rust 中,有三种不同类型的条件语句:ifif-elseif-else if-else

if 语句

if 语句用于测试一个条件是否为真,如果为真则执行一个代码块,否则会忽略代码块。其基本语法如下:

if <condition> {
    <code-block>
}

其中,<condition> 表示要测试的条件,可以是一个布尔表达式(例如,x > 0)、一个函数调用(例如,foo() == true)或某个变量的状态(例如,is_ready)。如果 <condition> 为真,那么 <code-block> 就会执行。

示例代码如下:

let x = 10;
if x > 0 {
    println!("x is greater than zero");
}

上述代码中,如果 x > 0 成立,则会输出字符串 x is greater than zero

if-else 语句

if-else 语句是 if 语句的扩展,当 <condition> 不满足时会执行 else 代码块。其基本语法如下:

if <condition> {
    <code-block-A>
} else {
    <code-block-B>
}

其中,<condition><code-block-A>if 语句相同,而 <code-block-B> 则是在 <condition> 不成立时要执行的代码块。

示例代码如下:

let x = 10;
if x > 5 {
    println!("x is greater than 5");
} else {
    println!("x is less than or equal to 5");
}

x 大于 5 时,会输出字符串 x is greater than 5,否则会输出字符串 x is less than or equal to 5

if-else if-else 语句

if-else if-else 语句用于测试多个条件,当其中一个条件成立时,会执行对应的代码块。其基本语法如下:

if <condition-A> {
    <code-block-A>
} else if <condition-B> {
    <code-block-B>
} else {
    <code-block-C>
}

其中,<condition-A> 是第一个条件,如果成立则执行 <code-block-A>;如果不成立,则测试下一个条件 <condition-B>,如果成立则执行 <code-block-B>;否则执行 <code-block-C>

示例代码如下:

let x = 10;
if x < 0 {
    println!("x is negative");
} else if x == 0 {
    println!("x is zero");
} else {
    println!("x is positive");
}

x 小于 0 时,会输出字符串 x is negative;当 x 等于 0 时,会输出字符串 x is zero;否则会输出字符串 x is positive

总结

Rust 的条件语句提供了三种不同类型的语句结构,分别是 ifif-elseif-else if-else。这些条件语句可以根据不同的条件执行不同的代码块,从而实现对控制流的灵活控制。