lifetime

Rust Higher-ranked function pointers

A function pointer can describe a callable that works across input lifetimes. Such a pointer can be specialized to an interface requiring one particular lifetime. This differs from a pointer that is already limited to static inputs. Expected output (not executed): 3 5 Why: The general pointer works for the local borrow and can also satisfy the static-only interface. Common mistake: Expecting the specialized pointer to be assignable back to the general type.

Formal Syntax & Structure

rust syntaxrust
for<'a> fn(&'a str) -> usize

Working Example

Example Snippetrust
fn count(s: &str) -> usize { s.chars().count() }fn main() {    let general: for<'a> fn(&'a str) -> usize = count;    let static_only: fn(&'static str) -> usize = general;    let local = String::from("box");    println!("{} {}", general(&local), static_only("label"));}
Rust Reference