Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

for loop in Rust

  • for

  • range

  • If we want to iterate over a set of elements, eg. a range of numbers, then we ususally use for.

  • 1..5 means the right-hand limit is NOT included.

  • 1..=5 means the right-hand limit is included

fn main() {
    for ix in 1..5 {
        println!("count {}", ix);
    }
    println!();
    for ix in 1..=5 {
        println!("count {}", ix);
    }
}
count 1
count 2
count 3
count 4

count 1
count 2
count 3
count 4
count 5