Skip to content

选择结构

if选择语句

rust
let number = 3;
if number < 5 {
    println!("condition was true");
}
rust
let number = 3;
if number < 5 {
    println!("condition was true");
} else {
    println!("condition was false");
}
rust
let number = 6;
if number % 4 == 0 {
    println!("number is divisible by 4");
} else if number % 3 == 0 {
    println!("number is divisible by 3");
} else if number % 2 == 0 {
    println!("number is divisible by 2");
}
rust
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {}", number);

匹配控制语句match

Rust没有switch,提供了更为强大的匹配控制语句match

rust
match value {
    pattern => expression,
    
    // 没有任何匹配的情况
    _ => expression,
}
rust
let x = 1;
match x {
    1 => println!("x is one"),
    2 => println!("x is two"),
    _ => println!("x is not one or two"),
}
rust
let x = 8;
match x {
    6 | 7 | 8 => println!("x is six or seven or eight"),
    _ => println!("x is something else"),
}
rust
let x = 4;
match x {
    1..=5 => println!("x is between 1 and 5"),
    _ => println!("x is something else"),
}
rust
enum Color {
    Red,
    Green,
    Blue,
}

fn main() {
    let color = Color::Red;
    match color {
        Color::Red => println!("The color is red!"),
        Color::Green => println!("The color is green!"),
        Color::Blue => println!("The color is blue!"),
    }
}
rust
let point = (0, 5);
match point {
    (0, 0) => println!("Origin"),
    (x, 0) => println!("On the X axis at {}", x),
    (0, y) => println!("On the Y axis at {}", y),
    (x, y) => println!("On neither axis: ({}, {})", x, y),
}
rust
let x = 5;
match x {
    n if n < 0 => println!("x is negative"),
    n if n > 10 => println!("x is greater than ten"),
    _ => println!("x is neither negative nor greater than ten"),
}

控制结构

rust
for x in 1..10 {
    println!("{}", x);
}
rust
let mut x = 1;
while x < 10 {
    x += 1;
    println!("{}", x);
}
rust
let mut x = 1;
loop {
    println!("loop {}", x);
    x += 1;
    if x > 20 {
        // 单独break
        break;
    }
}
rust
let mut x = 1;
let result = loop {
    x += 1;
    if x > 20 {
        break x;
    }
};
println!("result: {}", result);
rust
let mut count = 0;
# 循环标签必须'开头
'outer: for i in 0..10 {
    for j in 0..10 {
        println!("i={}, j={}", i, j);
        // 满足条件,跳出循环
        if i * j > 20 {
            break 'outer;
        }
        count += 1;
    }
}
println!("count: {}", count);

人生感悟