Rust has the standard loops one might expect, such as a while (conditional) style loop, and a for (counting) loop. As with most modern languages, it also has a for each style loop.
A Bad Type of Loop…
One thing that is unique however, is that it also includes a built in infinite loop, which many (myself include) consider to be bad form. You can use the continue
command to start the loop over, skipping any content after that line inside of the loop, as well as a break
, to exit the loop.
let mut count = 0;
println!("Let's count until infinity!");
// how long will this go on for???
loop {
count += 1;
println!("{}", count);
// I could put a break here... or there... or anywhere else if I want to make this difficult to debug.
}
Conditional Loops
A while loop is standard for Rust, and works like most languages, except there is no parenthesis for the condition, similar to how Rust handles conditional statements for their if statements.
This is an example of the famous fizzbuzz application.
fn main() {
// A counter variable
let mut n = 1;
// Loop while `n` is less than 101
while n < 101 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
// Increment counter
n += 1;
}
}
For (Counting) Loops
A for loop in Rust is similar to what you might see in Ruby, or some other newer languages, where you have a starting and ending condition. However, while the initial condition is inclusive, the external is not:
fn main() {
// `n` will take the values: 1, 2,up to 50
for n in 1..51 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}
If you want to include the final number, use ..=
.
fn main() {
// `n` will take the values: 1, 2,up to 51
for n in 1..=51 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}
For Each Style (Range)
Rust has a for ... in
style command, similar to other languages for each, where you can iterate over a series of data that allows iteration.
fn main() {
let names = ["Bruce", "Clark", "Diana"];
for name in names.iter() {
println!("Hello {}", name);
}
println!("names: {:?}", names);
}
Rust actually has several different types of iterators, but we’re just going to look at iter()
for this instance.
Loops in Rust was originally found on Access 2 Learn