Hi
I'm writing a code below, and got an Error....
The problem looks like that I am passing an iterator iter_borrowed_from
that shares the lifetime with the variable s
to fn my_method
of Box<dyn MyTrait>
.
The issue arises because my_method
might store iter_borrowed_from
somewhere. So It is not released even if my_method
ends.
I was wondering, Is there any way to tell the compiler my_method
is not storing iter_borrowed_from
?
Code:
use std::boxed::Box;
trait MyTrait<It> {
fn my_method(&self, it: It);
}
struct X {/* private fields */}
impl<It> MyTrait<It> for X {
fn my_method(&self, it: It) {
// private body
}
}
fn main() {
let dyn_trait: Box<dyn MyTrait<_>> = Box::new(X {});
let s: String = String::new();
let iter_borrowed_from = s.chars();
dyn_trait.my_method(iter_borrowed_from);
// iter_borrowed_from Drops here <-- ERROR? iter_borrowed_from is still being borrowed in dyn_trait.my_method
// s Drops here
// dyn_trait Drops here
}
Error:
error[E0597]: `s` does not live long enough
--> examples/calculator/src/main.rs:19:30
|
18 | let s: String = String::new();
| - binding `s` declared here
19 | let iter_borrowed_from = s.chars();
| ^ borrowed value does not live long enough
...
26 | }
| -
| |
| `s` dropped here while still borrowed
| borrow might be used here, when `dyn_trait` is dropped and runs the destructor for type `Box<dyn MyTrait<Chars<'_>>>`
|
= note: values in a scope are dropped in the opposite order they are defined
By the way, I was trying to implement 'virtual class wrapper' in C++...