Conditional Statement
An if expression is used to control which code gets executed based on conditions the program can evaluate at runtime.
Short hand to use if condition.
let y =true;
let x = if y {1} else {0};
println!("x is {}", x)
Output-
x is 1
Loop
Rust provides a loop keyword to indicate an infinite loop. Unless stopped manually or with a break staement, loop can go infinitely.
Infinite loop example. Manually stop the program
let mut count=0;
loop{
count += 1;
println!("count is {}", count)
}
break keyword
Immediately exit the loop and continue execution forward. The break statement can be used to prematurely exit all types of loop constructs.
Here once loop is at 10 it breaks the loop and continues further execution
let mut count=0;
loop{
if count == 10{
println!("breaking the loop on count {}", count);
break;
}
count += 1;
println!("count is {}", count);
}
println!("Continues execution.");
Output-
count is 1
count is 2
count is 3
count is 4
count is 5
count is 6
count is 7
count is 8
count is 9
count is 10
breaking the loop on count 10
Continues execution.
break with return
In the below code break can return the result or the reason the loop is stopped to the execution program.
let mut count=0;
let result = loop{
if count == 10{
println!("breaking the loop on count {}", count);
break count * 5
}
count += 1;
println!("count is {}", count);
};
println!("Count result is - {} * 5 = {}", count, result);
Output-
count is 1
count is 2
count is 3
count is 4
count is 5
count is 6
count is 7
count is 8
count is 9
count is 10
breaking the loop on count 10
Count result is - 10 * 5 = 50
Predicate (while) loop
Predicate loop that repeats a block of code while the condition is true. Begins by evaluating a boolean condition and breaks/completes when the condition is false. A while-loop repeats a block of code while a condition is true.
Here break statement can be used to terminate the loop but it doesnot return the value as comapred to loop
let mut count=0;
while count < 5 {
count += 1;
println!("count is {}", count);
}
Output
count is 1
count is 2
count is 3
count is 4
count is 5
Iterator for loop
The for in
construct can be used to iterate through an Iterator
. One of the easiest ways to create an iterator is to use the range notation a..b
. This yields values from a
(inclusive) to b
(exclusive) in steps of one.
For loops are mainly used to iterate over the items in a collection, and execute some code for each one so that you can process each item in the collection individually. If you need to repeat a block of code for a specific number of times that you know before starting the loop, you can use a ‘for’ loop to iterate over the range from zero to that value.
for n in 1..5{
print!("{}\t", n)
}
loop 1..5, here 1 is inclusive while 5 is exclusive. Print! won;t print in new line.
Output
1 2 3 4
user iter() methodto iterate over the list-
let message= ['r','u','s','t'];
for msg in message.iter(){
print!("{}\t", msg)
}
Output-
r u s t
Iterator with index
At times apart from the element in the array or list and index is required. This can be achieved by using enumerate() method
let message= ['r','u','s','t'];
for (index,msg) in message.iter().enumerate(){
println!("item {} is {}", index, msg)
}
Output-
item 0 is r
item 1 is u
item 2 is s
item 3 is t
Nested loops
Example here taking row and columns and printing those values in a nested loop i.e. for loop(rows) wthin for loop(columns)
let matrix = [[1,2,3],[10,20,30], [100,200,300]];
for row in matrix.iter(){
for col in row.iter(){
print!("{}\t", col);
}
println!();
}
Output-
All the columsn are printed in same line while row in new line.
variable.iter() is used to iterate between rows and columns
1 2 3
10 20 30
100 200 300
Modify the value in for loop using iter_mut()
Sometimes value in the collection needs to be updated. This can be done by iterating and updating the values. To do so use iter_mut() function as follows-
let mut matrix = [[1,2,3],[10,20,30], [100,200,300]];
for row in matrix.iter_mut(){
for col in row.iter_mut(){
*col += 5;
print!("{}\t", col);
}
println!();
}
Reference – https://dhghomon.github.io/easy_rust/Chapter_17.html
Notice here the iter_mut() method is used which give a reference to the mmeory allocated for the collection. In the next line *col is used to deference so that a addition operation can be performed.
UsingĀ *
Ā is called “dereferencing”.
Output-
6 7 8
15 25 35
105 205 305
Rust has two rules for mutable and immutable references. They are very important, but also easy to remember because they make sense.
- Rule 1: If you have only immutable references, you can have as many as you want. 1 is fine, 3 is fine, 1000 is fine. No problem.
- Rule 2: If you have a mutable reference, you can only have one. Also, you can’t have an immutable referenceĀ andĀ a mutable reference together.