I am truly confused by this minimal example. For the life(time) of me, I cannot figure out why this value does not live long enough.
The actual concrete return type of format_with_config() should be String in all of these minimal examples, however I'm trying to get it to work with impl Debug.
I even tried to be as explicit as possible that the return value is not tied to the lifetime of &self by declaring impl Debug + 'static.
The example works if you replace all of the impl Debug + 'static with String, so I know that the intent here is valid and logically sound, but I really would like to try to get this working with impl <trait>.
The function returns an owned value, so I don't understand why the compiler thinks the borrow is invalid. What else do I have to do here to make this work?
Thank you for any insights you might be able to share!
use core::fmt::Debug;
#[derive(Debug, Default)]
struct Config {}
#[derive(Debug)]
struct Configurable<'config, T> {
item: T,
config: &'config Config,
}
impl<'config, T> Configurable<'config, T> {
fn share_config<R>(&self, other: R) -> Configurable<'config, R> {
Configurable {
item: other,
config: self.config,
}
}
}
trait FormatWithConfig {
fn format_with_config<T: Debug>(&self, other: T) -> impl Debug + 'static;
}
#[derive(Debug, Clone)]
struct Value {}
impl<'config> FormatWithConfig for Configurable<'config, &Value> {
fn format_with_config<T: Debug>(&self, other: T) -> impl Debug + 'static {
format!("{:?}", other)
}
}
struct ValueWithCount<'value> {
value: &'value Value,
count: usize,
}
impl<'value, 'config> FormatWithConfig for Configurable<'config, ValueWithCount<'value>> {
fn format_with_config<T: Debug>(&self, other: T) -> impl Debug + 'static {
let configured_value = self.share_config(self.item.value);
configured_value.format_with_config(other)
}
}
fn main() {}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0597]: `configured_value` does not live long enough
--> src/main.rs:42:9
|
40 | fn format_with_config<T: Debug>(&self, other: T) -> impl Debug + 'static {
| - let's call the lifetime of this reference `'1`
41 | let configured_value = self.share_config(self.item.value);
| ---------------- binding `configured_value` declared here
42 | configured_value.format_with_config(other)
| ^^^^^^^^^^^^^^^^--------------------------
| |
| borrowed value does not live long enough
| argument requires that `configured_value` is borrowed for `'1`
43 | }
| - `configured_value` dropped here while still borrowed
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (bin "playground") due to previous error