English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Le espressioni condizionali nel linguaggio Rust hanno questo formato:
fn main() { let number = 3; if number < 5 { println!("La condizione è true"); } println!("La condizione è false"); } }
Nel programma menzionato sopra, c'è una condizione if, questa sintassi è comune in molti altri linguaggi, ma ci sono alcune differenze: prima di tutto, l'espressione condizionale number < 5 non richiede di essere inclusa tra parentesi (attenzione, non è obbligatorio, non è vietato); tuttavia, la sintassi if in Rust non esiste la regola di non utilizzare { per un singolo comando, non è permesso sostituire un blocco con un singolo comando. Nonostante ciò, Rust supporta la sintassi tradizionale else-if:
fn main() { let a = 12; let b; if a > 0 { b = 1; } else if a < 0 { b = -1; } else { b = 0; } println!("b is {}", b); }
Running Result:
b is 1
The conditional expression in Rust must be of bool type, for example, the following program is incorrect:
fn main() { let number = 3; if number { // Error, expected `bool`, found integer rustc(E0308) println!("Yes"); } }
Although the conditional expressions in C/C++ languages are represented by integers, either 0 or true, this rule is prohibited in many languages that pay attention to code safety.
combining with the function body expressions learned in previous chapters, we can associate with them:
if <condition> { block 1 } else { block 2 }
In this syntax, { block 1 } and { block 2 } Can it be a function body expression?
The answer is yes! That is, in Rust we can use the if-else structure to implement something similar to the ternary conditional expression (A ? B : C) Effect:
fn main() { let a = 3; let number = if a > 0 { 1 } else { -1 }; println!("number is {}", number); }
Running Result:
number is 1
NoteThe types of two function body expressions must be the same! And there must be an else and its subsequent expression block.