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.
Bạn sẽ học được gì
- if, else if, else
- Conditions must be bool
- if as an expression
score = 87
- 1
score >= 90false, skip - 2
score >= 70true - 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
- Conditions are checked from top to bottom.
- Only the first true branch runs.
- let grade = if ... { 'A' } else { 'B' }; stores the result.
Ví dụ Rust chạy được
Rust
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}");
}
Good
Grade: BLuyệ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ến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
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.
- Xếp Loại Chữ Chuyển điểm kiểm tra thành xếp loại chữ. Dễ
- Năm Nhuận Kiểm tra một năm có tuân theo quy tắc năm nhuận của lịch Gregory hay không. Dễ