Iterator & Extension Traits
Extension traits add methods to existing types (str, Iterator, third-party types) without wrapping. Iterator adapters compose zero-cost data pipelines.
Search across all documentation pages
Extension traits add methods to existing types (str, Iterator, third-party types) without wrapping. Iterator adapters compose zero-cost data pipelines.
trait IterExt: Iterator {
fn collect_vec(self) -> Vec<Self::Item> where Self: Sized { self.collect() }
}
impl<I: Iterator> IterExt for I {}When to reach for this: Ergonomic helpers on types you do not own; reusable iterator utilities.
trait StrExt {
fn trimmed_nonempty(&self) -> Option<&str>;
}
impl StrExt for str {
fn trimmed_nonempty(&self) -> Option<&str> {
let t = self.trim();
if t.is_empty() { None } else { Some(t) }
}
}
let ids: Vec<u64> = records.iter().filter_map(|r| r.id).collect();What this demonstrates:
collect/sumfilter_map, try_fold) before customBlanket impls: impl<T: AsRef<str>> StrExt for T {} for wider coverage. For iterators, Iterator::map + collect beats manual loops unless profiled.
filter. Fix: use std adapters.collect::<Vec<_>>() or turbofish.copied() for Copy items.| Alternative | Use When | Don't Use When |
|---|---|---|
| Free functions | No method ergonomics needed | Fluent API desired |
| Wrapper newtype | Many methods on one type | Single helper on str |
itertools crate | Rich adapters | Simple one-liner std |
Inherent on your type; extension for others you cannot modify.
tuple_windows, intersperse - add dep when std insufficient.
StreamExt from futures for async pipelines.
Your trait + your blanket on foreign type is allowed.
Avoid std-like names that may conflict later.
Iterator adapters zero-cost in release when inlined.
Short-circuit Result processing without collect-then-validate.
into_iter() on Option yields 0-1 items.
Different iterator model; use Polars expr API not manual IterExt.
Assert on collect::<Vec<_>>() outputs for adapter chains.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 19, 2026