Fondamenti di 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.
Cosa imparerai
- 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.
Punti chiave
- Conditions are checked from top to bottom.
- Only the first true branch runs.
- let grade = if ... { 'A' } else { 'B' }; stores the result.
Esempio Rust eseguibile
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: BEsercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
- Letter Grade Turn a test score into a letter grade. Facile
- Anno Bisestile Verifica se un anno segue la regola bisestile del calendario gregoriano. Facile