pub struct Writer<'a> {
target: &'a mut String,
}
impl<'a> Writer<'a> {
fn indent<'b>(&'b mut self) -> &'a String {
self.target
}
}
Compiling this code results in the following error:
error: lifetime may not live long enough
--> src/bin/main29.rs:19:9
|
17 | impl<'a> Writer<'a> {
| -- lifetime `'a` defined here
18 | fn indent<'b>(&'b mut self) -> &'a String {
| -- lifetime `'b` defined here
19 | self.target
| ^^^^^^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b`
|
= help: consider adding the following bound: `'b: 'a`
Why can't this Rust code be compiled? I thought it would work.
&'a mut Stringcan't be copied, and it can't be moved out ofselfwhenselfis&mut. Movingselfso it is consumed will allow you to moveself.targetout and avoid the lifetime issue: Playground. (I don't have time to turn this into an answer. Please feel free to yourself if it works for you.)