loading

Rust Loop

Loops

The concept of loops comes into play if we wish to run the block of statements more than once. A loop runs the code contained in its body until it reaches its conclusion, at which point it restarts right where it left off.

Rust consists of three kinds of loops:

loop

It is not a conditional loop, is it? This keyword instructs Rust to keep running the code block repeatedly unless you manually end the loop explicitly.

Syntax of loop

				
					 loop{  
  //block statements  
}  
				
			

Block statements are run an unlimited number of times in the syntax above.

Flow diagram of loop:

Rust Loop -

Example

				
					fn main()  
  
 loop  
 {  
     println!("Hello javaTpoint");  
}  
				
			

Output:

				
					Hello javaTpoint
Hello javaTpoint
Hello javaTpoint
Hello javaTpoint
.
.
.
infinite times
				
			

In this example, until we explicitly end the loop, “Hello javaTpoint” is printed again. The “ctrl+c” command is typically used to end a loop.

Termination from loops

To break out of the loop, use the ‘Break’ keyword. The loop will run endlessly if the ‘break’ keyword is not used.

Example

				
					fn main()  
  
 let mut i=1;  
 loop  
 {  
       println!("Hello javaTpoint");  
       if i==7   
       {  
         break;  
       }  
 i+=1;  
 }}  
				
			

Output:

				
					Hello javaTpoint
Hello javaTpoint
Hello javaTpoint
Hello javaTpoint
Hello javaTpoint
Hello javaTpoint
Hello javaTpoint
				
			

The fact that i is a mutable variable in the example above indicates that the counter variable is subject to change for use in the future.

Share this Doc

Rust Loop

Or copy link

Explore Topic