Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


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.


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


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);


Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring