Iterators and closures in Rust

Learn Rust · Beginner · 12 min · After Lifetimes in Rust: how long a reference lives

How do you transform a collection without writing the loop yourself?

  1. 1Guess

    fn main() {
        let v = vec![1, 2, 3, 4];
        let s: i32 = v.iter().filter(|x| **x % 2 == 0).map(|x| x * x).sum();
        println!("{s}");
    }
    
    What does this program print?
  2. 2Read

    Closures

    A closure is an anonymous function you can store in a variable or pass around: |x| x + n. Unlike a plain function it can capture variables from where it is written. By default it borrows them. Put move before the bars and it takes ownership instead, which you need when the closure outlives the variables. A parameter of type impl Fn(i32) -> i32 accepts a closure.

  3. 3Code

    Capturing by reference and by move

    1 / 2
    fn apply(f: impl Fn(i32) -> i32, value: i32) -> i32 {
        f(value)
    }
    
    fn main() {
        let n = 10;
        let add_n = |x| x + n;
        println!("{}", add_n(5));
        println!("{}", apply(add_n, 1));
    
        let name = String::from("Ferris");
        let greet = move || format!("Hello, {name}!");
        println!("{}", greet());
    }
    

    Read the program. What will it print?

    Run it in the playground

  4. 4Read

    Lazy iterators

    An iterator produces items one at a time. It is lazy: map, filter, enumerate and zip are adapters that only describe a chain. Nothing runs until a consumer such as collect, sum, count or a for loop pulls the items. iter() borrows the items, and into_iter() takes ownership of them.

  5. 5Code

    Iterator chains

    1 / 2
    fn main() {
        let sentence = "the quick brown fox jumped";
        let lengths = sentence
            .split_whitespace()
            .map(|w| w.len())
            .collect::<Vec<_>>();
        println!("{lengths:?}");
        for (i, word) in sentence.split_whitespace().enumerate() {
            println!("{i}: {word}");
        }
        let total = lengths.iter().fold(0, |acc, n| acc + n);
        println!("total {total}");
        let longest = sentence.split_whitespace().max_by_key(|w| w.len());
        println!("{longest:?}");
    }
    

    Read the program. What will it print?

    Run it in the playground

  6. 6Fix

    fn main() {
        let v = vec![1, 2, 3];
        for x in v {
            println!("{x}");
        }
        println!("{} numbers", v.len());
    }
    
    This program does not compile. What is the bug?
  7. 7Say it back

  8. 8Mission · 10 min

    From a list of words, using only iterator chains, print how many there are, the longest word and the words longer than 4 letters in upper case.

    cargo new word-stats
    cd word-stats
    cargo run

Common questions

What is a closure in Rust?
A closure is an anonymous function written with bars, like |x| x + 1. It can capture variables from the scope around it, by reference by default or by ownership with the move keyword. You can store it in a variable or pass it to a function that takes impl Fn, for example to transform each item of a collection.
What does lazy mean for Rust iterators?
Iterator adapters such as map and filter do no work when you call them. They only build a new iterator. The items are produced when a consumer like collect, sum, count or a for loop asks for them. So you can chain many steps and the data is walked once, item by item.
What is the difference between iter and into_iter?
iter() borrows the collection and gives references to its items, so the collection stays usable afterwards. into_iter() takes ownership and gives the items themselves, so the collection is moved and cannot be used again. A for loop over a vector uses into_iter, and a for loop over &vector uses iter.

Sources

Measured with rustc 1.100.1 (play.rust-lang.org, stable, edition 2024) on 2026-12-03

Published Dec 3, 2026 · Updated Dec 3, 2026

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer