Iterators and Closures
Lesson 22 of 48 in Coddy's Rust for C Developers course.
An iterator produces items on demand. Adapters such as map and filter are lazy; a consumer such as collect, sum or any drives them. iter() borrows items, iter_mut() yields mutable references, and into_iter() consumes an owned vector. A closure uses |arguments| expression and can capture values from its surrounding scope. Rust infers whether it needs to borrow, mutably borrow or own a captured value. any stops at the first true result, so later elements are not visited. In C you often write the loop directly or pass a function pointer with a separate context pointer; Rust closures carry their captured context with their type.
C
#include <stdio.h>
#include <stddef.h>
struct Search { int limit; size_t visited; };
int above(int value, struct Search *context) {
++context->visited;
return value > context->limit;
}
int main(void) {
int values[] = {2, 9, 12};
struct Search search = {5, 0};
int found = 0;
for (size_t i = 0; i < 3; ++i) {
if (above(values[i], &search)) { found = 1; break; }
}
printf("%d %zu\n", found, search.visited);
return 0;
}Rust
fn main() {
let values = vec![2, 9, 12];
let limit = 5;
let mut visited = 0;
let found = values.iter().any(|&value| { visited += 1; value > limit });
println!("{} {}", if found { 1 } else { 0 }, visited);
}Creating an iterator does not run its work. Also check whether a closure receives values or references; adding a copy step for small integers can simplify later adapters.
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 C 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