Rust Tutorials: Iterator Adaptors (map, filter)

beginner
11 min

Rust Tutorials: Iterator Adaptors (map, filter)

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Iterator Adaptors in Rust. We'll explore the map and filter adaptors, learning how they can help us manipulate iterators with ease. Let's get started!

What are Iterator Adaptors? šŸŽÆ

In Rust, Iterator Adaptors are traits that modify existing iterators, allowing us to perform various operations without needing to rewrite our code. They are a powerful tool for transforming, filtering, and structuring data.

The map Adaptor šŸ’”

The map adaptor applies a function to each item of the iterator, effectively transforming the type of the items.

Example: Converting a vector of integers to a vector of string representations šŸ“

rust
let numbers = vec![1, 2, 3, 4, 5]; let strings: Vec<String> = numbers.iter().map(|num| num.to_string()).collect(); println!("{:?}", strings); // Output: ["1", "2", "3", "4", "5"]

šŸ’” Pro Tip: In this example, iter() is used to create an iterator over the numbers vector. |num| num.to_string() is the closure that transforms each integer into a string. The collect() function is used to collect the transformed items into a new vector.

Quiz

What does the closure |num| num.to_string() do in the provided example?

  • Multiplies each number by 2
  • Converts each number to its string representation
  • Sorts the numbers in ascending order

Correct: Converts each number to its string representation

The filter Adaptor šŸ“

The filter adaptor creates an iterator that only includes items that satisfy a specific condition.

Example: Filtering out odd numbers from a vector šŸ“

rust
let numbers = vec![1, 2, 3, 4, 5]; let odd_numbers: Vec<i32> = numbers.iter().filter(|num| num % 2 != 0).collect(); println!("{:?}", odd_numbers); // Output: [1, 3, 5]

šŸ’” Pro Tip: In this example, iter() is used to create an iterator over the numbers vector. |num| num % 2 != 0 is the closure that checks if a number is odd. The collect() function is used to collect the filtered items into a new vector.

Quiz

What does the closure |num| num % 2 != 0 do in the provided example?

  • Multiplies each number by 2
  • Returns true if the number is odd, otherwise false
  • Adds 1 to each number

Correct: Returns true if the number is odd, otherwise false

Remember, with practice and patience, you'll master Iterator Adaptors in no time! Stay tuned for more Rust tutorials here at CodeYourCraft. Happy coding! šŸ’»šŸŒŸ