Iteration in RUST — Working with Loop, While, For

Knoldus Inc.
Knoldus - Technical Insights
2 min readAug 3, 2018

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 loop, as

  • 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.

[gist https://gist.github.com/bhavya411/c5fb481de8802f8b18dfed830f9f4505]

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

[gist https://gist.github.com/bhavya411/2cb3a13671af7e6f01dcb6c6f00332cd/]

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:

[gist https://gist.github.com/bhavya411/6a48407ac8ebfeb7bce9dea29827e7c8/]

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:

[gist https://gist.github.com/bhavya411/274981a7b3a7b19a6b94f6bccb78a99f/]

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.

Reference: Control Flow — The Rust Programming Language

knoldus-advt-sticker

--

--

Knoldus Inc.
Knoldus - Technical Insights

Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage | www.knoldus.com