Control Flow
Rust has most of the control flow expressions you may expect, and a few you may not.
if
if
Compared to other curly-brace languages (like C++, Java, and JavaScript), Rust’s if
statements have two notable differences:
Lack of the requirement for the condition expression to be enclosed in parentheses.
Example
if
structures in Rust can be expressions as well as just normal statements. That is, they can resolve to a value like a ternary expression in JavaScript.Example
while
& loop
while
& loop
Rust has three looping structures. loop
is the simplest: it just loops forever until it hits a break
. while
, like its namesake in other languages, loops while a condition holds (or until it hits a break
). Similarly in style to the if
statement, the while
condition does not need to be enclosed in parentheses.
The third looping structure is the for
loop. It operates on any iterable type.
Arrays:
for i in [2, 4, 6, 8] { println!("{i}"); }
Output:
2 4 6 8
Ranges:
for i in 0..5 { println!("{i}"); }
Output:
0 1 2 3 4
There are other iterable structures, like [Vec](<https://doc.rust-lang.org/std/vec/struct.Vec.html>)
and [HashSet](<https://doc.rust-lang.org/std/collections/struct.HashSet.html>)
, which you can explore if you wish.
match
match
Instead of the switch
statement found in many other common languages, Rust opted for the more “functional” match
construct.
`let operator = "*";
match operator { "+" => println!("add"), "-" => println!("subtract"), "*" => println!("multiply"), "/" => println!("divide"), _ => println!("unknown"), // _
is the catch-all pattern }`
While matching against input cases using Rust’s pattern matching syntax, you can also extract pieces from the input data using destructuring.
`enum MediaType { Movie, Series { episodes: u32 }, }
let media_type: MediaType = /* ... */;
match media_type { MediaType::Movie => println!("It's a movie!"), // single line terminated with comma MediaType::Series { episodes } => { // multi-line enclosed in curly braces println!("It's a TV show!"); println!("It has {episodes} episodes!"); } }`
match
expressions, since they are expressions, can also resolve to a value:
let unit_count = match media_type { MediaType::Series { episodes } => episodes, _ => 1, };
if let
if let
A special version of the if
expression can perform destructuring as well. It’s like a conditional let
.
This is equivalent to the previous listing:
let unit_count = if let MediaType::Series { episodes } = media_type { episodes } else { 1 };
Last updated