What is the difference between using as_str on a function's output or on a variable?

Viewed 356

I am writing a Rust function to get configuration from a file, this is the function:

pub fn getConfig(key: &str) -> String {
    let mut settings = config::Config::default();
    settings.merge(config::File::with_name("settings")).unwrap()
        .merge(config::Environment::with_prefix("APP")).unwrap();
    let hashConfig = settings.try_into::<HashMap<String, String>>().unwrap();
    let conn = hashConfig.get(key).unwrap();
    let std =String::from(conn);
    return std;
}

When I use this function like this:

fn main() {
    let config = getConfig("key");
    let conf = config.as_str();
    print!("{}",config)
}

it works fine. But when I use the function like this:

fn main() {
    let config = getConfig("key").as_str();
    print!("{}",config)
}

It shows an error:

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:30:18
   |
30 |     let config = getConfig("key").as_str();
   |                  ^^^^^^^^^^^^^^^^         - temporary value is freed at the end of this statement
   |                  |
   |                  creates a temporary which is freed while still in use
31 |     print!("{}",config)
   |                 ------ borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

What is the difference? Why should I write to a variable first? why should not use as_str directly after the function?

1 Answers

GetConfig returns an owned value which then you take a ref to with as_ref. But the problem is that nothing is really owning it, so the reference gets invalidated. You want to have a variable to own the value, and later you can get the reference to that value which is already owned.

Related