Rust cơ bản

Rust if, else if and else

Run code only when a condition is true, and use if as an expression that returns a value.

  • Cơ bản
  • Đọc trong 2 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • if, else if, else
  • Conditions must be bool
  • if as an expression
score = 87
  1. 1score >= 90false, skip
  2. 2score >= 70true
  3. 3"Good"this branch runs

The first true branch runs

An if statement runs a block only when its condition is true. The condition must be a bool: Rust does not treat numbers as true or false.

The conditions are checked from top to bottom and only the first true branch runs, so 87 prints Good. Because if is an expression, it can produce a value for let: every branch must then return the same type.

Những điểm quan trọng

  1. Conditions are checked from top to bottom.
  2. Only the first true branch runs.
  3. let grade = if ... { 'A' } else { 'B' }; stores the result.

Ví dụ Rust chạy được

Rust
Chạy code →
main.rs
fn main() {
    let score = 87;

    if score >= 90 {
        println!("Excellent");
    } else if score >= 70 {
        println!("Good");
    } else {
        println!("Keep practicing");
    }

    let grade = if score >= 90 { 'A' } else if score >= 80 { 'B' } else { 'C' };
    println!("Grade: {grade}");
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
Good
Grade: B

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Tiếp theo: FizzBuzz →

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách