Higher-ranked trait bounds
Quick answer
A higher-ranked trait bound requires a trait implementation for every lifetime chosen by the caller. Use it when an operation must accept temporary borrows without tying them to one external lifetime.
Quantify over lifetimes
F: for<'a> Fn(&'a str) -> usize means F accepts a string borrow of any lifetime and returns a length. Elided lifetimes in many Fn bounds express this same higher-ranked relationship. The bound does not require the string itself to live forever.
fn apply<F>(f: F) -> usize where F: for<'a> Fn(&'a str) -> usize { let s = String::from("hello"); f(&s)}fn main() { println!("{}", apply(str::len)); }Expected stdout (not executed):
5The function creates the borrow after receiving the callable.
fn apply<F: for<'a> Fn(&'a str)>(_: F) {}fn static_only(_: &'static str) {}fn main() { apply(static_only); }Expected: compilation fails; exact diagnostic not verified.
A callable restricted to static inputs does not meet the universal bound.
Common mistake
A lifetime parameter declared outside a bound is not automatically universally quantified inside it.
Try it yourself
Write a higher-ranked callable that accepts any borrowed slice of i32 and returns its length.
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
Higher-ranked trait bounds — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A callback must accept a borrow from each newly created local String. Which bound expresses this?
Higher-ranked trait bounds — 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 apply<F>(f: F) -> usize where F: for<'a> Fn(&'a str) -> usize { let s = String::from("hello"); f(&s) } fn main() { println!("{}", apply(str::len)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Higher-ranked trait bounds — 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 apply<F: for<'a> Fn(&'a str)>(_: F) {} fn static_only(_: &'static str) {} fn main() { apply(static_only); } ``` Which outcome or interpretation best matches this example?