I am using a trait with a method that returns an boxed iterator. Since the iterator will use self
and the parameters of foo
, all are constrained to the same lifetime:
pub trait Foo {
fn foo<'a>(&'a self, txt: &'a str) -> Box<Iterator<Item = String> + 'a>;
}
I would like to build a function around this method:
fn foo_int<'a, F: Foo>(f: &'a F, val: i32) -> impl Iterator<Item = String> + 'a {
let txt = format!("{}", val);
f.foo(&txt)
}
But that does not compile, because:
error[E0515]: cannot return value referencing local variable `txt`
--> src/lib.rs:7:5
|
7 | f.foo(&txt)
| ^^^^^^----^
| | |
| | `txt` is borrowed here
| returns a value referencing data owned by the current function
I understand why this happens, and it makes sense, but it seems to be that there should be a way to get around it. After all, that's what closures (with the move
keyword) do: they take ownership of the values they need to "take away with them".
Is there a clever way to rewrite the foo_int
function, using a closure or something else?