rust / expert
Snippet
HRTB (Higher-Rank Trait Bounds) for Abstracting Lifetimes in Closure Arguments
This example shows how to use Higher-Rank Trait Bounds (HRTB) with the `for<'a>` syntax. By using HRTB, we specify that the closure must accept a reference with any lifetime `'a` (specifically, lifetimes internal to `execute_with_borrow`), rather than being locked into a single specific lifetime chosen by the caller.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
pub fn execute_with_borrow<F>(f: F)wherefor<'a> F: Fn(&'a str) -> &'a str,{let local_data = String::from("temporary string");let result = f(&local_data);println!("Processed result: {}", result);}fn main() {execute_with_borrow(|s| {if s.len() > 5 {&s[..5]} else {s}});}
Breakdown
1
for<'a> F: Fn(&'a str) -> &'a str
Declares that the closure type `F` must be callable with a reference of *any* lifetime `'a`.
2
let local_data = String::from("...")
A local string allocated inside the function scope.
3
let result = f(&local_data)
Passes a reference to `local_data` to the closure. The lifetime of this reference is local to this function call.
4
|s| if s.len() > 5 { &s[..5] } else { s }
The closure borrows the input reference and returns a slice tied to that same arbitrary lifetime.