Make my function to be able to accept "any" closure
⚓ Rust 📅 2025-12-22 👤 surdeus 👁️ 6In Rust, I can make my function to accept a closure that is required to return an instance of some trait, say, Debug:
fn f(p: impl Fn(&str) -> Box<dyn Debug>) {}
Such function seems to work:
f(|b| Box::new("static")); //< works
However, it can't accept a closure that returns a value borrowed from the closure's argument:
f(|b| Box::new(b)); //< doesn't work
Neither it can accept a closure that returns a value borrowed from the outer context:
let a = &"a".to_owned();
// f(|b| Box::new(a)); //< doesn't work
I know how to make my function to be able to accept a closure that returns a value borrowed from the closure's argument:
fn f(p: impl for<'t> Fn(&'t str) -> Box<dyn 't + Debug>) {}
f(|b| Box::new("static")); //< works
f(|b| Box::new(b)); //< also works
However, such function still can't accept a closure that returns a value borrowed from the outer context.
Also, I know how to make my function to be able to accept a closure that returns a value borrowed from the outer context:
fn f<'t>(p: impl 't + Fn(&str) -> Box<dyn 't + Debug>) {}
f(|b| Box::new("static")); //< works
let a = &"a".to_owned();
f(|b| Box::new(a)); //< also works
However, such function can't accept a closure that returns a value borrowed from the closure's argument.
How can I write a function that is able to accept a closure that returns a value borrowed from the closure's argument, and is able to accept a closure that returns a value borrowed from the outer context, and is able to accept a closure that returns a value borrowed from both? E.g.:
fn f<???>(p: ???) {}
f(|b| Box::new("static")); //< must work
f(|b| Box::new(b)); //< must work too
let a = &"a".to_owned();
f(|b| Box::new(a)); //< must work too
f(|b| Box::new((a, b))); //< must work too
6 posts - 3 participants
🏷️ Rust_feed