Hello! I´m studying the differences between &str and String and memory allocation concept.
The code below will issue the "temporary value being referenced and then dropped" error:
use chrono::{DateTime, Local};
#[derive(Debug)]
struct User<'a> {
timestamp: &'a str,
}
impl<'a> User<'a> {
fn set_timestamp(&mut self) {
let local_time: DateTime<Local> = Local::now();
self.timestamp = &format!(
"{}-{}",
local_time.format("%d/%m/%Y"),
local_time.format("%H:%M")
);
}
}
fn main() {
let mut fred = User { timestamp: "" };
fred.set_timestamp();
dbg!(&fred);
}
The error:
Compiling playground v0.0.1 (/playground)
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:11:27
|
8 | impl<'a> User<'a> {
| -- lifetime `'a` defined here
...
11 | self.timestamp = &format!(
| _________-_________________^
| |_________|
| ||
12 | || "{}-{}",
13 | || local_time.format("%d/%m/%Y"),
14 | || local_time.format("%H:%M")
15 | || );
| || ^- temporary value is freed at the end of this statement
| ||_________|
| |__________creates a temporary which is freed while still in use
| assignment requires that borrow lasts for `'a`
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
If the struct's member is converted to a String, then it will work. Of course, then there will be memory allocation.
But isn´t the format! macro already making memory allocation anyway?
So is there any problem with just using String as the member type? Or is there any other solution to this?
Thank you a lot!