Thank you rustlings! I finally understood iterators 🚀

188 points lemsoe 34 comments

Coming from C# and Go I always had my problems really *getting* iterators in Rust. Going through rustlings a second time, I finally solved the second quiz and now I feel like it clicked! Just wanted to share my notes, maybe they help someone else too. 🙂

My solution for rustlings quiz 2:

pub fn transformer(input: Vec<(String, Command)>) -> Vec<String> {  
    input  
        .into_iter()  
        .map(|(s, c)| match c {  
            Command::Uppercase => s.to_uppercase(),  
            Command::Trim => s.trim().to_string(),  
            Command::Append(amount) => s + &"bar".repeat(amount),  
        })  
        .collect()  
}

Explanation of the Steps

.into_iter()

  • Creates a consuming iterator.
  • The original vector gives up its elements → we now own the Strings.
  • Important because s + "bar" consumes the string (ownership).
  • After calling this, the original vector can no longer be used.

.map(|(s, c)| match c { ... })

  • Applies a function to each element.
  • Destructures the tuple (s, c) into the string s and the command c.
  • Depending on the command, produces a new String:
    • Uppercase → converts the string to uppercase.
    • Trim → removes leading and trailing whitespace.
    • Append(amount) → appends "bar" amount times.

.collect()

  • Collects the results of the iterator.
  • Builds a new vector: Vec<String>.

Iterator Comparison

Method Returns Ownership Typical Use Case
.iter() &T Borrow only When you just want to read elements
.iter_mut() &mut T Mutable borrow When you want to modify elements in place
.into_iter() T Ownership When you want to consume/move elements

TL;DR

  • Use .iter() when you only need to look at elements.
  • Use .iter_mut() when you want to modify elements in place.
  • Use .into_iter() when you need ownership and want to consume or move elements.