Iteration in RUST – Working with Loop, While, For

Reading Time: 2 minutes

I hope you have already been through the following blogs in order to learn control flow and iteration in RUST:

Basically, RUST is no different compared to other programming languages in the context of loops and iteration, if you have already worked with any language like C, C++, Java, Scala, etc. then it will be much easier and quicker to go through this blog and get ready for handling the control flow of your logic.

Majorly, RUST has 3 kinds of loops: loop, while and for. 

let’s, start with the loop: It is much similar to do loopas

  • It will always have atleast one execution,
  • It will execute the block of code forever until we explicitly ask it to stop.
  • If we don’t provide condition within the block to stop, the program will run for infinite and we need to stop the whole program execution.

Above code will never terminate, to terminate it either you need to press ctrl+c or change the code to provide an explicit condition to break the flow as below

Although the loop is not a preferred way as it may lead to an infinite execution problem, the second kind of loop is while which requires a condition:

Hope you are able to locate the major difference with loop and while.

The last and the most powerful is for which have multiple use cases, the safety and conciseness of for loops make them the most commonly used loop construct in Rust.

It is much different from for loop of other languages and much similar to for-each loop, basically, it needs an iterator to fetch values one by one, let’s explain it with the example:

Here, we are in a much safer state, as we are not required to declare an index variable, increment it with each iteration, and explicitly giving a condition for iteration. In other programming languages if we have iterated over an index which is greater than the size of the array then it will create a panic situation, but in rust, while dealing with for & iterator it will never exceed the index limit and only process the limited indexes.

Summary: I think you have already realized when to use for, while or loop, the best and safest is using for as it assures us for the index limit,  dealing with while  can create panic situations if the condition isn’t given properly and  loop  needs even more careful handling as it can lead to infinite execution.

ReferenceControl Flow – The Rust Programming Language



Written by 

Sourabh Verma is a Software Consultant with experience of more than 2 years. He has a deep understanding of Java and familiar with Spring Framework, JPA, Hibernate, JavaScript, Spark, Scala, AngularJS, Angular 4. He is an amazing team player with self-learning skills and a self-motivated professional. He loves to play with Real-time problems, Big data, Cloud computing, Agile Methodology and Open Source Technology. He is eager to learn new technologies and loves to write blogs and explore nature.