Rust Programming
If we want to execute the block of statements more than once, then loops concept comes under the role. A loop executes the code present inside the loop body till the end and starts again immediately from the starting.
Rust consists of three kinds of loops:
- loops
- for loop
- while loop
Loop Expression
In Rust, we use the loop expression to indefinitely execute a block of code. If we use a loop, the code execution inside of the loop code block doesn't stop and runs forever.
The syntax of the loop expression is:
loop {// code to execute}{codeBox}
Let's see an example.
fn main() {// loop expressionloop {println!("Loop forever!");}}{codeBox}
Output
Loop forever!Loop forever!Loop forever!...{codeBox}
This example code will print "Loop forever!" indefinitely unless the user terminates the program. Since the loop runs forever, it is also known as an infinite loop.
Terminating Loop in Rust
We use the break keyword to terminate a loop. For example,
fn main() {// initiate an infinite looploop {println!("Loop forever!");// stop infinite loopbreak;}}{codeBox}
Output
Loop forever!{codeBox}
Here, the break keyword terminates the loop. That is why the println! macro is executed only once