beginnerFlow Control
If Else
Conditional branching with if, else if, and else.
If Else
Conditional branching with if, else if, and else.
Difficulty
Beginner
Code
rust
fn main() {
let number = 7;
if number < 0 {
println!("negative");
} else if number == 0 {
println!("zero");
} else {
println!("positive");
}
let x = if true { 1 } else { 0 };
println!("x = {}", x);
}Explanation
This example demonstrates how to use if else in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the flow-control category to build a complete understanding of this topic.