Opaque types and lifetime capture
Quick answer
Return-position impl Trait hides one concrete return type behind a trait contract. Lifetime capture determines which generic parameters that hidden type is allowed to depend on.
Rust 2024 capture rules
For ordinary return-position impl Trait in Rust 2024, in-scope generic parameters including lifetimes are captured automatically unless precise capture is specified. use<> can exclude an unneeded lifetime when there are no other required captures. Capturing a lifetime does not mean the hidden type necessarily contains a reference, but it affects what the caller may assume.
fn words(s: &str) -> impl Iterator<Item = &str> { s.split_whitespace() }fn main() { println!("{}", words("a b c").count()); }Expected stdout (not executed):
3The iterator borrows its input.
fn number(_: &str) -> impl std::fmt::Display + use<> { 7 }fn main() { let x; { let s = String::from("temp"); x = number(&s); } println!("{x}");}Expected stdout (not executed):
7The return contract does not capture the temporary input lifetime.
Common mistake
Do not assume impl Trait permits unrelated concrete types in different return branches.
Try it yourself
Return an iterator over a borrowed array, then explain why it cannot outlive the array.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Opaque types and lifetime capture — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A returned opaque type should not capture an unused input lifetime in edition 2024. What can express that intent?
Opaque types and lifetime capture — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn words(s: &str) -> impl Iterator<Item = &str> { s.split_whitespace() } fn main() { println!("{}", words("a b c").count()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Opaque types and lifetime capture — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn number(_: &str) -> impl std::fmt::Display + use<> { 7 } fn main() { let x; { let s = String::from("temp"); x = number(&s); } println!("{x}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.