-3

When I using this code in Rust:

fn main() {
    let s = String::from("hello").as_str();
    println!("slice: {}", s); 
}

the compiler shows error:

temporary value dropped while borrowed
creates a temporary value which is freed while still in userustcClick for full compiler diagnostic
main.rs(2, 43): temporary value is freed at the end of this statement
main.rs(3, 27): borrow later used here
main.rs(2, 5): consider using a `let` binding to create a longer lived value: `let binding = String::from("hello");
`, `binding`

does the as_str did not copy the value? I think the s will live util the main function end. why still told that long live issue?

Dolphin
  • 29,069
  • 61
  • 260
  • 539

1 Answers1

2

does the as_str did not copy the value?

No, this is exactly the difference between String and &str. String owns the value, &str is only a reference. &str is incapable of owning a value, it only references the String. And because you didn't store the String in a variable, it gets dropped while the &str still exists, which leads to the error.

Your code is equivalent to this one:

fn main() {
    let x: String = String::from("hello");
    let s: &str = x.as_str();
    drop(x);
    println!("slice: {}", s);
}
error[E0505]: cannot move out of `x` because it is borrowed
 --> src\main.rs:4:10
  |
2 |     let x: String = String::from("hello");
  |         - binding `x` declared here
3 |     let s: &str = x.as_str();
  |                   ---------- borrow of `x` occurs here
4 |     drop(x);
  |          ^ move out of `x` occurs here
5 |     println!("slice: {}", s);
  |                           - borrow later used here

If you store the String in a variable, it works fine:

fn main() {
    let x: String = String::from("hello");
    let s: &str = x.as_str();
    println!("slice: {}", s);
}
slice: hello

More info about the difference of String and str can be found here: What are the differences between Rust's `String` and `str`?

Finomnis
  • 18,094
  • 1
  • 20
  • 27