1

Why is this an issue? What is the ownership problem?

fn test_code() -> String {
    let mut mod_string = "";

    let y = ["", "", " "];

    for x in &y {
        if x.to_string() == " " {
            // getting temp value dropped below... why?
            mod_string = &(mod_string.to_owned() + &x.to_string() + ",");
        }
    }

    mod_string.to_string()
}
error[E0716]: temporary value dropped while borrowed
  --> src/lib.rs:9:27
   |
9  |             mod_string = &(mod_string.to_owned() + &x.to_string() + ",");
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^- temporary value is freed at the end of this statement
   |                           |
   |                           creates a temporary which is freed while still in use
...
13 |     mod_string.to_string()
   |     ---------- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user241619
  • 25
  • 5
  • Does this https://stackoverflow.com/questions/54056268/temporary-value-is-freed-at-the-end-of-this-statement answer you question? (it's kind of the same case here - your owned string that you concatenate with is fried, when you try to borrow it at the same time) – lpiepiora May 05 '21 at 19:41

1 Answers1

3

You're trying to maintain an &str, which won't work, since &str is a string slice and thus must point to existing data. You want the variable to own the data, so maintain a String instead:

fn test_code() -> String {
    // convert to String here
    let mut mod_string = "".to_owned();

    let y = ["", "", " "];

    for x in &y {
        if x.to_string() == " " {
            mod_string = mod_string + x + ",";
        }
    }

    // no longer need to convert to String here
    mod_string
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55