Iterators and Closures
Lesson 22 of 48 in Coddy's Rust for JavaScript Developers course.
JavaScript array methods are eager. filter builds a new array as soon as it is called, and map then builds another, running each callback at once. Rust iterator adapters such as filter and map are lazy: they only describe the work, and the closures run when a consumer such as collect asks for values. The examples log inside the mapping closure to show the difference: JavaScript maps before printing built, and Rust maps after. Both languages let a closure read variables from the surrounding scope. A JavaScript closure captures the variable itself and sees whatever value it holds when the callback runs. A Rust closure captures each variable in the least demanding way its body needs, here a shared borrow of floor, unless you write move to transfer the captured values into the closure. values.iter() yields references, so the array is only borrowed and is still usable afterwards. The filter closure receives a reference to each item, which is why it dereferences twice. The annotation on result tells collect which collection to build.
Complete standalone JavaScript program:
const values = [4, 9, 2];
const floor = 3;
const kept = values.filter((v) => v > floor).map((v) => {
console.log("map", v);
return v - floor;
});
console.log("built");
console.log(kept.join(","));
JavaScript output:
map 4
map 9
built
1,6
Complete standalone Rust program:
fn main() {
let values = [4, 9, 2];
let floor = 3;
let kept = values.iter().filter(|v| **v > floor).map(|v| {
println!("map {}", v);
v - floor
});
println!("built");
let result: Vec<i32> = kept.collect();
println!("{:?}", result);
}
Rust output:
built
map 4
map 9
[1, 6]
Challenge
EasyImplement pub fn excess(values: &[i32], floor: i32) -> Vec<i32> in pipeline.rs. Preserve order, select values strictly greater than floor, and return each selected value minus the floor. Do not change the input. Input is a floor followed by zero or more integers, all from -1000 to 1000. solve returns comma-separated results or empty when none remain. Implement the transformation through the public API; it must work for subslices, empty slices and repeated calls with different floors.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, pipeline.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod pipeline;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
let values = vec![17, -4, 8, 8, 3];
assert_eq!(pipeline::excess(&values[1..], 3), vec![5, 5]);
assert_eq!(pipeline::excess(&values[1..], -4), vec![12, 12, 7]);
assert_eq!(pipeline::excess(&[], 9), Vec::<i32>::new());
assert_eq!(pipeline::excess(&[4, 4], 4), Vec::<i32>::new());
assert_eq!(values, vec![17, -4, 8, 8, 3]);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for JavaScript Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler