I have a struct that contains a string that is used to format dates with chrono::DateTime.format()
:
struct DateThingy {
format: String,
}
impl DateThingy {
fn new(format: String) -> Self {
Self { format }
}
}
This is a bit of a waste since the format string has to be parsed every time I format a date. To be more efficient, I figured I should parse the format string once and store the result instead. Then I can format using chrono::DateTime::format_with_items
:
use chrono::format::strftime::StrftimeItems;
use chrono::format::Item;
struct DateThingy<'a> {
items: Vec<Item<'a>>,
}
impl<'a> DateThingy<'a> {
fn new(format: String) -> Self {
Self {
items: StrftimeItems::new(&format).collect(),
}
}
}
This does not work:
error[E0515]: cannot return value referencing function parameter `format`
--> src/lib.rs:10:9
|
10 | / Self {
11 | | items: StrftimeItems::new(&format).collect(),
| | ------- `format` is borrowed here
12 | | }
| |_________^ returns a value referencing data owned by the current function
I can change the signature of new
to fn new(format: &'a str) -> Self
to get rid of the error, but now the creator of a DateThingy
must make sure that the format string is alive for long enough and mess around with lifetimes. I just want the DateThingy
to own all the information it needs, without relying on references or lifetimes.
How do I accomplish that?
The creation of the DateThingy
is not performance critical, so I am happy to clone string, allocate, store them, etc., if that helps.