Iterators and Closures
Lesson 22 of 48 in Coddy's Rust for Java Developers course.
Java streams and Rust iterators both support lazy processing. Creating a pipeline does not necessarily visit its elements; a consuming operation drives evaluation. Rust closures use vertical bars around parameters, while Java lambdas use an arrow. Rust closures can borrow, mutably borrow or own captured values, and those captures affect which callable traits they implement. Java captures local variables only when they are final or effectively final.
The examples ask whether any element matches a condition. any and Java anyMatch can stop at the first match instead of processing the entire collection. Rust iter() borrows elements, so its closure receives a reference here. The explicit dereference *n reads the integer. The collection remains usable because this pipeline does not consume its owned vector.
Java: complete program
class Main {
public static void main(String[] args) {
int floor = 5;
boolean found = java.util.stream.IntStream.of(1, 8, 3).anyMatch(n -> n > floor);
System.out.println(found);
}
}Rust: complete program
fn main() {
let floor = 5;
let values = vec![1, 8, 3];
let found = values.iter().any(|n| *n > floor);
println!("{}", found);
}Pitfall: Rust closures are not all plain function pointers. A closure capturing environment generally needs a callable trait rather than a fn pointer.
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 Java 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