lifetime
Rust Contravariance of function inputs
A function pointer accepting a broader set of inputs can stand in for one accepting a narrower set. For lifetime-bearing input types, the subtype direction is reversed. This is useful when adapting a callback to an interface with a stronger input guarantee. Expected output (not executed): Ready Why: The callback can accept any reference promised by the narrower interface. Common mistake: Assigning a callback requiring permanent data to an interface that may pass local data.
Formal Syntax & Structure
rust syntaxrust
fn(T) -> ()Working Example
Example Snippetrust
fn adapt<'a, 'b: 'a>(f: fn(&'a str), label: &'b str) { let narrowed: fn(&'b str) = f; narrowed(label);}fn print_label(label: &str) { println!("{label}"); }fn main() { adapt(print_label, "Ready"); }