2

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?

E_net4
  • 27,810
  • 13
  • 101
  • 139
Dolphin
  • 29,069
  • 61
  • 260
  • 539
  • `let config = getConfig("key")` keeps the value alive. `let conf = config.as_str()` is valid because the lifetime of `config` can be proved to outlive `conf`. But if you Inline its value, calling `getConfig("key")` returns a temporary that only lives until the end of the statement. If allowed, `conf` would have a dangling pointer, because it outlives the data it relies on. – Alexander Oct 28 '21 at 14:54

1 Answers1

1

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.

Netwave
  • 40,134
  • 6
  • 50
  • 93