Fn trait, lifetime, and HRTB

The Fn() -> T trait has a method (roughly speaking) of the type fn call(&self) -> T. I'd like to create a closure whose call method has the type fn call<'a>(&'a self) -> &'a T and name the trait it implements, but I can't: something like

let x = "three".to_string();
let f = move || &x;

fails to compile. Is there a way around this?

this line moves x into the closure and the closure returns reference to a local variable, which will not pass the borrow checker. it's semantically same as

fn f() -> &'??? str {
    let x = "".to_string();
    &x
}

This is not possible because the Fn trait is a subtrait of FnOnce, which means it has to additionally support being called as (self) -> Output.

It's theoretically possible to write a closure that supports returning borrowed data that originated outside it (e.g., if your example was not move) but then the closure itself will have a limited lifetime.

If you need precisely this signature, I suggest forgoing the closure sugar and just writing your own trait.

4 Likes

what you described sounds like the Borrow trait to me, but I'm not sure it can be achieved with the Fn trait,

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.