Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

for
loops
rust

For loop in Rust

Educative Answers Team

Imagine a situation where you have to print something a hundred times. How would you do it?

You could type the command a hundred times or copy-paste it repeatedly; but, that would be quite tedious. This is where loops come in. When using a for loop, hundreds of lines of code can be written in as few as three to four statements.

A for loop allows a particular set of statements​, written inside the loop, to be executed repeatedly until a specified condition is satisfied.

Syntax

A For loop in Rust works a bit differently than it does in other system languages. For starters, it does not look like a typical C for loop (see syntax below):

for variable in expression {
    loop code
}

A for loop’s expression in Rust is an iterator that ​returns a series of values. Each element is one iteration of the loop. This value is then bound to variable and can be used inside the loop code to perform operations. Once the loop code has been executed, the next value is fetched from the iterator and the process is repeated. The loop terminates when there are no more values.

svg viewer

Code

The code snippet below illustrates the usage of a for loop in Rust:

fn main() {
  // for loop to print the value of iterators
  for x in 0..10 {
    println!("value of iterator is: {}", x);
  }
}

RELATED TAGS

for
loops
rust
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring