Return impl Iterator From Functions
Functions can hand back an owning iterator typed as impl Iterator: callers depend only on the item type while the internal chain stays swappable.
Code
// 返回 impl Iterator:调用方只依赖 Item 类型,内部链可随时替换
fn slugs_from_titles(titles: Vec<String>) -> impl Iterator<Item = String> {
titles
.into_iter()
.filter(|t| !t.trim().is_empty())
.map(|t| t.trim().to_lowercase().replace(' ', "-"))
}
fn main() {
let titles = vec![
"Rust Iterator Adaptors".to_string(),
" ".to_string(),
"Return Impl Iterator".to_string(),
];
// 所有权随迭代器一起移交:collect 之后 titles 已被消费
let slugs: Vec<String> = slugs_from_titles(titles).collect();
for slug in &slugs {
println!("{}", slug);
}
println!("count: {}", slugs.len());
}How the snippet works
Count the functions slugs_from_titles and main as the entire surface area of Return impl Iterator From Functions.
Repetition is confined to for slug in &slugs — the rest of the file is straight-line.
Applying it
Signature: fn slugs_from_titles(titles: Vec<String>) -> impl Iterator<Item = String>
Each run prints the 1 labeled block count: in source order.
The entry point wires slugs_from_titles together — run it once and the whole demo flows.
Statements that matter
fn slugs_from_titles(titles: Vec<String>) -> impl Iterator<Item = String> {
titles
.into_iter()
.filter(|t| !t.trim().is_empty())
.map(|t| t.trim().to_lowercase().replace(' ', "-"))
}
let slugs: Vec<String> = slugs_from_titles(titles).collect();
FAQ
- What does Return impl Iterator From Functions print when run?
- Run it as a complete program — the output lines carry labels such as `count:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.