Основы Rust
Rust if, else if and else
Run code only when a condition is true, and use if as an expression that returns a value.
Что вы узнаете
- 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.
Главное
- Conditions are checked from top to bottom.
- Only the first true branch runs.
- let grade = if ... { 'A' } else { 'B' }; stores the result.
Пример на Rust, который можно запустить
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: BПрактика
Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.
Закончили этот урок?
Отметьте его как изученный, чтобы следить за прогрессом.
Ваш прогресс сохранён в этом браузере Войдите, чтобы он был доступен на всех устройствах.
Попрактикуйтесь на задаче
Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.
- Letter Grade Turn a test score into a letter grade. Легко
- Високосный год Проверьте, соответствует ли год григорианскому правилу високосного года. Легко