if-else
- Rust course
- Beginner
- Lesson 36/115
- 4 min
Branch with if, else if and else.
if-else
An if condition needs no parentheses but must be a bool; Rust doesn't turn numbers into true/false on its own:
let sicaklik = 24;
if sicaklik > 30 {
println!("sıcak");
} else if sicaklik > 15 {
println!("ılık");
} else {
println!("soğuk");
}if n { ... } (n a number) is a compile error; write if n != 0.
if as an expression
An if expression is used to choose a value and bind it directly:
let yas = 16;
let bilet = if yas < 18 { 25 } else { 40 };
println!("{bilet} TL");Complex conditions are combined with &&, || and !; thanks to short-circuiting, v.len() > 0 && v[0] == 1 doesn't panic on an empty vector.
Practice Ticket price
Write fn bilet(yas: u32) -> u32: return 0 under 6, 25 under 18, and 40 otherwise (with an if/else if/else expression). Print bilet(4), bilet(12) and bilet(30) on one line.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn bilet(yas: u32) -> u32 {
if yas < 6 {
0
} else if yas < 18 {
25
} else {
40
}
}
fn main() {
println!("{} {} {}", bilet(4), bilet(12), bilet(30));
}Expected output
0 25 40
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why doesn't <code>let x = if true { 1 } else { "bir" };</code> compile?
- It compiles
- The arms have different types (i32 and &str) Correct answer
- true can't be a constant
- else is unnecessary
Explanation: Because if is an expression it must have a single type; every arm must produce the same type.
2 Middle condition
if n > 0 {
println!("pozitif");
} ____ n < 0 {
println!("negatif");
}
if n > 0 {
println!("pozitif");
} else if n < 0 {
println!("negatif");
}
Explanation: An extra condition is written with else if.
3 Temperature and output
| Term | Meaning |
|---|---|
35 |
sıcak (hot) |
24 |
ılık (mild) |
5 |
soğuk (cold) |
if n {} |
Compile error |