bhylu.com

Advertisements

Rust Iterators and collect

Describe a transformation without manually managing indexes.

How it works

Iterators produce values through a sequence of operations. Many adapters are lazy: constructing an iterator does not necessarily run the mapping work until it is consumed. iter borrows, iter_mut borrows mutably and into_iter often consumes an owned collection. Choose the ownership behaviour deliberately, then use a terminal operation such as collect, sum or for_each.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

iterators.rs

fn main() {
    let counts = vec![3_u32, 5, 8];
    let doubled: Vec<u32> = counts.iter().map(|n| n * 2).collect();
    assert_eq!(doubled, vec![6, 10, 16]);
    assert_eq!(counts.len(), 3);
    println!("Borrowed counts transformed to 6, 10, 16");
}

Expected result

Borrowed counts transformed to 6, 10, 16

The original vector remains available because iter supplied shared references. The collected result owns its transformed integers. The explicit Vec<u32> annotation states the requested output collection. Avoid putting surprising side effects in a lazy chain unless evaluation order and consumption are clear to the reader.

Primary technical reference: Rust documentation.