Difference between revisions of "Rust-Programming-Language/C2/Iterators-and-Closures/English"
(Created page with "{| border="1" |- || '''Visual Cue''' || '''Narration''' |- || '''Slide 1''' || Welcome to the Spoken Tutorial on '''Iterators and Closures''' in''' Rust.''' |- style="border:1...") |
|||
| Line 29: | Line 29: | ||
|| | || | ||
* <div style="margin-left:1.27cm;margin-right:0cm;">The following code file is required to practise this tutorial.</div> | * <div style="margin-left:1.27cm;margin-right:0cm;">The following code file is required to practise this tutorial.</div> | ||
| − | + | * <div style="margin-left:1.27cm;margin-right:0cm;">iterators.rs</div> | |
* <div style="margin-left:1.27cm;margin-right:0cm;">This file is provided in the Code Files link of this tutorial page.</div> | * <div style="margin-left:1.27cm;margin-right:0cm;">This file is provided in the Code Files link of this tutorial page.</div> | ||
Revision as of 18:44, 13 October 2025
| Visual Cue | Narration |
| Slide 1 | Welcome to the Spoken Tutorial on Iterators and Closures in Rust. |
| Slide 2
Learning Objectives |
In this tutorial, we will learn about:
|
| Slide 3
System Requirements To record this tutorial I’m using |
To record this tutorial I’m using the following setup. |
| Slide 5
Code Files |
|
| Slide 6:
Iterators |
Let us get started.
|
| Slide 7:
Type of Iterators |
In Rust we can categorize iterators into 3 main types.
|
|
Let’s learn about Basic and Range Iterators with an example. | |
| Open Visual code editor | Open the Visual Studio code editor. |
| In the menu bar, click on Terminal and select New Terminal. | In the menu bar, click on Terminal and select New Terminal. |
| I have created the filehandling project as explained earlier. | Let us go to our working directory MyRustProject as explained earlier.
Type the command cargo new iterators and press Enter. Open the created project as shown. |
| Point to the main.rs file. | In the main.rs file, copy and paste the code from the Code file. |
| fn main() {
let numbers = vec![1, 2, 3]; let mut iter = numbers.iter(); println!("{:?}", iter.next()); // Some(1) println!("{:?}", iter.next()); // Some(2) println!("{:?}", iter.next()); // Some(3) println!("{:?}", iter.next()); // None } |
We declared a vector called numbers with values 1, 2, 3.
numbers.iter() method creates an iterator named iter. iterator can safely access vector elements without looping. next() method is used to traverse through the items. It returns a value None when it reaches the end of the collection. Save the program. |
| Run the code to see the output. | |
| Let’s see an example of commonly used iterator adapters.
Clear the previous code. Copy paste the code from the code file. | |
| fn main() {
let numbers = vec![1, 2, 3, 4, 5]; let squared: Vec<i32> = numbers .iter() .map(|x| x * x) .collect(); println!("{:?}", squared); // [1, 4, 9, 16, 25] } |
We declare a vector of integers.
We then create an iterator using the .iter() method. It gives us immutable references to each element in the vector. .map() method uses a closure that takes each element x and returns its square This doesn't immediately compute the square. It builds a new iterator pipeline that knows how to compute them when needed. Finally, .collect() consumes the iterator and gathers the squares into a new vector |
| Run the code to see the output.
The result is printed as a new vector [1, 4, 9, 16, 25] | |
| Let’s see an example of Iterator Consumers or Collectors.
These methods consume an iterator and return results like Vec, bool, or a single value. | |
| Copy and paste the code from the code file. | |
| fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6]; let evens: Vec<_> = numbers .iter() .filter(|x| *x % 2 == 0) .collect();
} |
This program shows how to use iterators with filters to show only even numbers from a vector.
Filter() method which takes a closure that returns true or false for each element. The condition that we’ve used here will check if the number is even or not. Only the elements that satisfy this condition are passed forward in the iterator pipeline. Lastly, .collect() method gathers the remaining elements into new vector evens. Save the program. |
| In the terminal, type cargo run and see the output.
The result is [2, 4, 6], it contains only even numbers from the original list. | |
| Slide 6:
Closures
|
Next we will see about Closures.
|
| Let us understand closures with an example.
Switch back to the visual code editor. Clear the window and copy and paste the code from the codefile. | |
| fn main() {
// define a closure and store it in a variable let add_one = |x: i32| x + 1; // call closure and store the result in a variable let result = add_one(2); println!("Result = {}", result); } |
Here, parameters are placed between vertical pipelines.
We have defined a closure and binded it to the add_one variable. We then call the closure with add_one(2) and bind the return value to the result variable. Closures can omit type annotations and return types, as Rust is capable of type inference Save the program. |
| Run the code to see the output. | |
| Let us see another example for multiple statements inside a closure. | |
| Clear the previous code. Copy paste the code from the code file. | |
| fn main() {
// define a multi-line closure let squared_sum = |x: i32, y: i32| { // find the sum of two parameters let mut sum: i32 = x + y; // find the squared value of the sum let mut result: i32 = sum * sum; return result; }; // call the closure let result = squared_sum(5, 3); println!("Result = {}", result); } |
In this example, we enclose the multiple statements using curly braces {}.
First we calculate the sum of two parameters. Then we find the squared value of the sum. Save the program. |
| In the terminal, type cargo run.
We can see the output as 64. That is the sum of 5 and 3 is 8. The squared value is 64. | |
| This brings us to the end of this tutorial.
Let us summarize. | |
Slide 8
let numbers = vec![10, 15, 20, 25, 30, 35, 40];
|
As an assignment,
|
| Slide 9 Thank You | Thanks for joining. |