0

The following code compiles:

fn main() {
    let directory_key = "a";
    let object_key = "b";
    let filepath = Path::new(&format!("{}/{}", directory_key, object_key));
    // println!("{:?}", filepath);
}

However, if the println! line is commented in, the code encounters a compile-time error:

fn main() {
    let directory_key = "a";
    let object_key = "b";
    let filepath = Path::new(&format!("{}/{}", directory_key, object_key));
    println!("{:?}", filepath);
}
error[E0716]: temporary value dropped while borrowed
   --> src/s3.rs:196:31
    |
196 |     let filepath = Path::new(&format!("{}/{}", directory_key, object_key));
    |                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
    |                               |
    |                               creates a temporary which is freed while still in use
197 |     println!("{:?}", filepath);
    |                      -------- borrow later used here
    |
    = note: consider using a `let` binding to create a longer lived value
    = note: this error originates in the macro `format` (in Nightly builds, run with -Z macro-backtrace for more info)

The error can be resolved by, as the compiler suggests, introducing a let binding to the result of format!. The below code demonstrates this solution:

fn main() {
    let directory_key = "a";
    let object_key = "b";
    let filepath_string = format!("{}/{}", directory_key, object_key);
    let filepath = Path::new(&filepath_string);
    println!("{:?}", filepath);
}

Why does the E0717 error happen for the code from the second snippet? Does it have something to do with how format! works?

Darnock
  • 69
  • 3
  • 1
    _"Does it have something to do with how `format!` works?"_ It returns a `String`. If it is not retained in a variable, it is dropped just after it was created. – E_net4 Sep 08 '22 at 09:14

0 Answers0