How To Make a For Loop and Range in Rust
Created
Modified
Using while Expression
A while loop begins by evaluating the boolean loop conditional operand.
fn main() {
let mut i = 0;
while i < 3 {
println!("{}", i);
i += 1;
}
// Vec
let mut x = vec![1, 2, 3];
while let Some(y) = x.pop() {
println!("{}", y)
}
// Empty
// warning: irrefutable `while let` pattern
while let _ = 5 {
// do Something
break;
}
}
0 1 2 3 2 1
Using for Pattern in Expression
A for expression is a syntactic construct for looping over elements provided by an implementation of std::iter::IntoIterator. For example,
fn main() {
let v = &["Apple", "Google"];
for text in v {
println!("{}", text)
}
// a series of integers
for i in 1..3 {
println!("{}", i)
}
}
Apple Google 1 2
Using loop Expression
A loop expression denotes an infinite loop. For example,
fn main() {
// loop expression
loop {
println!("Infinite loops");
break;
}
// Result
let mut i = 0;
let result = loop {
if i >= 3 {
break i;
}
i += 1;
println!("Infinite");
};
println!("{}", result);
}
Infinite loops Infinite Infinite Infinite 3
Range expressions
Examples:
fn main() {
// Range expressions
// 1..2; // std::ops::Range
// 3..; // std::ops::RangeFrom
// ..4; // std::ops::RangeTo
// ..; // std::ops::RangeFull
// 5..=6; // std::ops::RangeInclusive
// ..=7; // std::ops::RangeToInclusive
let x = std::ops::Range { start: 0, end: 2 };
let y = 0..2;
for i in y {
println!("{}", i)
}
}
0 1
The .. and ..= operators will construct an object of one of the std::ops::Range (or core::ops::Range) variants, according to the following table:
Syntaxstart..endstd::ops::Range start ≤ x < endstart..std::ops::RangeFrom start ≤ x..endstd::ops::RangeTo x < end..std::ops::RangeFull -start..=endstd::ops::RangeInclusive start ≤ x ≤ end..=endstd::ops::RangeToInclusive x ≤ end