
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Loop Keyword in Rust Programming
Rust provides a loop keyword that allows us to run an infinite loop. The infinite loop indicated by the help of the loop keyword can be broken by the use of the break keyword. Also, we can exit an iteration and continue the infinite loop with the help of the continue keyword.
Example
Consider the example shown below −
fn main() { let mut count = 0u32; println!("Infinite loop begins!!"); // Infinite loop loop { count += 1; if count == 4 { println!("four"); continue; } println!("{}", count); if count == 7 { println!("OK, that's enough!!"); break; } } }
Output
Infinite loop begins!! 1 2 3 four 5 6 7 OK, that's enough!!
Nesting and Labels
Rust also provides us with a unique feature with which we can break or continue the outer loop execution from inside the nested loops. In order to do that, we just need to‘label’ the loops.
Example
Consider the example shown below −
#![allow(unreachable_code)] fn main() { 'outerloop: loop { println!("Entered - outer loop"); 'innerloop: loop { println!("Entered - inner loop"); // This breaks the outer loop break 'outerloop; } println!("This line will never be printed"); } println!("Exited the outer loop"); }
Output
Entered - outer loop Entered - inner loop Exited the outer loop
Advertisements