Use A Basic Loop In Rust
Code snippet for how to Use A Basic Loop In Rust with sample and detail explanation
Rust, a popular systems programming language, offers various mechanisms for repetitive tasks, including loops. This article will demonstrate a simple example of using a basic loop in Rust.
Code Snippet: Use a Basic Loop in Rust
Let’s start with a simple snippet of a basic loop in Rust:
fn main() {
for i in 1..11 {
println!("Number: {}", i);
}
}
Code Explanation: Use a Basic Loop in Rust
The given Rust code snippet demonstrates a simple loop - more specifically, a for
loop.
Let’s break down the code step by step:
-
Function Declaration: The first line
fn main() {
starts the declaration of the main function. This is the starting point for all Rust programs. -
Loop Initialization: The second line
for i in 1..11 {
starts thefor
loop. The..
operator creates a range of values. In this case, it creates a sequence of numbers from 1 to 10 (Rust ranges are exclusive of the ending number). Thei
is the control variable that takes each value in the range, one by one. -
Under Loop Operation: The third line
println!("Number: {}", i);
is the operation to be performed in each iteration of the loop. Theprintln!
macro prints out the number of the current iteration. The{}
inside the string is a placeholder that gets replaced by the value ofi
. -
Ending the Loop and the Function: The last two lines
}
simply mark the end of thefor
loop and the main function respectively.
Try to run this Rust program, and it will print the numbers from 1 to 10, showing how you can achieve basic iteration in Rust using a for
loop.