lifetime

Rust Return-position impl Trait capturing a borrow

An opaque return type exposes an interface while leaving its concrete implementation hidden. If that implementation borrows the input, the returned iterator cannot be used after the source becomes invalid. No dynamic dispatch is required by this syntax. Expected output (not executed): pack ship Why: The iterator borrows the text and yields string slices. Common mistake: Assuming a hidden type implies an owned or heap-allocated result.

Formal Syntax & Structure

rust syntaxrust
fn words<'a>(s: &'a str) -> impl Iterator<Item = &'a str>

Working Example

Example Snippetrust
fn words<'a>(text: &'a str) -> impl Iterator<Item = &'a str> {    text.split_whitespace()}fn main() {    let note = String::from("pack ship");    for word in words(&note) { println!("{word}"); }}
Rust Reference