Temporary value dropped while still being in use

One sentence describing the issue: I DON'T UNDERSTAND IT.
When I look at the problematic line, I actually do what compiler suggests. I do use let statement to bind result from unwrap to the dn variable. Yet, I'm getting error. Why is that. Can somebody explain that to me?
Thanks

 pub fn set_dir_info(&self, file_info: &gio::FileInfo) {
        let dn:Option<&str> = file_info.name().to_str();
        match dn {
            Some(s) => {
                println!("dn: {}", s);
            }
            None => {
                println!("dn None")
            }
        }
}

error[E0716]: temporary value dropped while borrowed
--> src/application_row/mod.rs:67:18
|
67 | let dn = file_info.name().to_str();
| ^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
68 | match dn {
| -- borrow later used here
|
= note: consider using a let binding to create a longer lived value

67 | let dn = file_info.name().to_str();
   |          ^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement

The error message points out precisely what you need to extract into a separate let binding.

So:

let file_name = file_info.name();
let dn = ...

file_info.name() returns owned value, then with to_str you are taking reference to it. But this owned value lives only in this expression and is dropped immediately at the end of it. To use reference later, you need to put this owned value somewhere, so as proposed by compiler and previous comment, you should first put it on stack with let, and then you can take references with to_str, as_str, ... till the end of scope, function in this case.

Thanks, that works indeed.

Thanks for the detailed explanation. I get it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.