rust-closures-iterators
Skill4 starsChanged 3 months agoApache-2.0View on GitHub
Master closures and iterators in Rust. Use when writing functional-style code, implementing custom iterators, using iterator adaptors, understanding Fn/FnMut/FnOnce traits, or optimizing iterator chains.
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 0 are distinctive, and 1 is very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
1
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 48
Every Fn is also FnMut and FnOnce.
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Closures & Iterators
Based on The Rust Programming Language Ch. 13, Effective Rust, and the Iterator trait documentation.
When to Use This Skill
- Writing closures with correct capture semantics
- Understanding
Fn,FnMut,FnOncetrait hierarchy - Chaining iterator adaptors for data transformation
- Implementing
Iteratorfor custom types - Using
collect()effectively - Performance of iterator chains vs loops
Closures
Capture Modes
let name = String::from("Alice");
let numbers = vec![1, 2, 3];
// Borrow (&T) — Fn
let print = || println!("{name}"); // captures &name
// Mutable borrow (&mut T) — FnMut
let mut acc = 0;
let mut add = |x| { acc += x; }; // captures &mut acc
// Move (T) — FnOnce
let consume = move || drop(numbers); // takes ownership of numbersFn Trait Hierarchy
FnOnce (can be called once — may consume captured values)
↑
FnMut (can be called multiple times — may mutate captures)
↑
Fn (can be called multiple times — only reads captures)Every Fn is also FnMut and FnOnce. Compiler picks the least restrictive trait.
Closure Types in APIs
// Accept any callable (most flexible for callers)
fn apply<F: FnOnce() -> T, T>(f: F) -> T { f() }
// Accept reusable callable
fn repeat<F: Fn() -> T, T>(f: F, n: usize) -> Vec<T> {
(0..n).map(|_| f()).collect()
}
// Accept mutating callable
fn fold<F: FnMut(Acc, Item) -> Acc>(mut f: F, init: Acc, items: &[Item]) -> Acc { ... }move Closures
Force ownership transfer (required for threads, async):
let data = vec![1, 2, 3];
let handle = std::thread::spawn(move || {
println!("{data:?}"); // data moved into closure
});Returning Closures
fn make_adder(x: i32) -> impl Fn(i32) -> i32 {
move |y| x + y
}
// Dynamic dispatch (multiple possible closures)
fn get_transform(kind: &str) -> Box<dyn Fn(i32) -> i32> {
match kind {
"double" => Box::new(|x| x * 2),
"negate" => Box::new(|x| -x),
_ => Box::new(|x| x),
}
}Iterators
The Iterator Trait
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// 75+ provided methods (map, filter, fold, collect, etc.)
}Creating Iterators
let v = vec![1, 2, 3];
v.iter() // yields &i32
v.iter_mut() // yields &mut i32
v.into_iter() // yields i32 (consumes v)
// Ranges
(0..10) // 0 to 9
(0..=10) // 0 to 10
('a'..='z') // char rangeKey Adaptors (Lazy — No Work Until Consumed)
let result: Vec<_> = items.iter()
.filter(|x| x.is_valid()) // keep matching elements
.map(|x| x.transform()) // transform each element
.take(10) // limit to first 10
.skip(2) // skip first 2
.enumerate() // add index: (i, item)
.flat_map(|(i, x)| x.children()) // flatten nested iterators
.chain(extra.iter()) // append another iterator
.zip(other.iter()) // pair with another iterator
.inspect(|x| println!("{x:?}")) // debug peek (no modification)
.collect();Consuming Methods (Drive the Iterator)
iter.count() // number of elements
iter.sum::<i32>() // sum all elements
iter.product::<i32>() // multiply all elements
iter.min() / iter.max() // find extremes
iter.any(|x| predicate(x)) // short-circuit OR
iter.all(|x| predicate(x)) // short-circuit AND
iter.find(|x| x.id == 5) // first matching element
iter.position(|x| x > 10) // index of first match
iter.fold(init, |acc, x| acc + x) // general reduction
iter.for_each(|x| process(x)) // side effectscollect() Power
// Into Vec
let v: Vec<_> = iter.collect();
// Into HashMap
let map: HashMap<_, _> = pairs.into_iter().collect();
// Into String
let s: String = chars.collect();
// Into Result<Vec<T>, E>
let results: Result<Vec<_>, _> = items.iter().map(parse).collect();Custom Iterator
struct Fibonacci { a: u64, b: u64 }
impl Fibonacci {
fn new() -> Self { Self { a: 0, b: 1 } }
}
impl Iterator for Fibonacci {
type Item = u64;
fn next(&mut self) -> Option<u64> {
let result = self.a;
let new_b = self.a + self.b;
self.a = self.b;
self.b = new_b;
Some(result)
}
}
// Usage
let first_10: Vec<_> = Fibonacci::new().take(10).collect();Performance
Iterator chains are zero-cost abstractions — they compile to the same assembly as hand-written loops. The compiler fuses adaptors into a single pass (no intermediate allocations).
// These generate identical machine code:
let sum: i32 = v.iter().filter(|&&x| x > 0).sum();
let mut sum = 0;
for &x in &v { if x > 0 { sum += x; } }Reference Map
references/closure-semantics.md— capture modes, Fn traits, move, higher-order functionsreferences/iterator-adaptors.md— all adaptors with examplesreferences/custom-iterators.md— implementing Iterator, IntoIterator, DoubleEndedIterator
Key References
In this repository80 other files it gives its agents.
- a11y-accessibility-designSkill
- agentic-ui-patternsSkill
- ai-native-ui-designSkill
- ai-ui-anti-patternsSkill
- ai-ui-heuristicsSkill
- calm-technology-uiSkill
- conversion-growth-designSkill
- cross-platform-designSkill
- dark-mode-designSkill
- data-visualizationSkill
- design-systemsSkill
- design-thinking-processSkill
- error-empty-statesSkill
- ethical-design-patternsSkill
- form-uxSkill
- information-architectureSkill
- interaction-design-patternsSkill
- internationalization-uiSkill
- mobile-touch-designSkill
- modal-classes-lifecycleSkill
- modal-container-imagesSkill
- modal-dicts-queuesSkill
- modal-endpointsSkill
- modal-fundamentalsSkill
- modal-gpu-computeSkill
- modal-networkingSkill
- modal-observabilitySkill
- modal-parallel-executionSkill
- modal-sandboxesSkill
- modal-scaling-performanceSkill
- modal-schedulingSkill
- modal-secretsSkill
- modal-serversSkill
- modal-storageSkill
- modal-web-servingSkill
- modal-workspace-adminSkill
- motion-design-principlesSkill
- notifications-permissionsSkill
- onboarding-uxSkill
- rust-api-designSkill
- rust-async-programmingSkill
- rust-cargo-masterySkill
- rust-cli-applicationsSkill
- rust-clippy-lintsSkill
- rust-compiler-internalsSkill
- rust-concurrencySkill
- rust-design-patternsSkill
- rust-editionsSkill
- rust-embeddedSkill
- rust-error-handlingSkill
- rust-game-developmentSkill
- rust-lifetimes-borrowingSkill
- rust-macrosSkill
- rust-performanceSkill
- rust-rustdocSkill
- rust-rustup-toolchainSkill
- rust-smart-pointersSkill
- rust-testing-benchmarkingSkill
- rust-type-systemSkill
- rust-unsafe-ffiSkill
- The first 60 shown.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

