简体   繁体   中英

Rust - How does String::from() actually work?

I'm still new to rust so there are some stuff about it I still don't know

I'm trying to split a String value and pass it to a variable like so:

let mut splitted_line = String::from("something=random").split("=");
let key = splitted_line.nth(0).expect("incorrect line format");
let value = splitted_line.nth(1).expect("incorrect line format");

The code above raise the following error:

error[E0716]: temporary value dropped while borrowed
  --> src\main.rs:49:37
   |
49 |             let mut splitted_line = String::from("something=random").split("=");
   |                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^           - temporary value is freed at the end of this statement
   |                                     |
   |                                     creates a temporary which is freed while still in use
...
55 |             let key = splitted_line.clone().nth(0).expect("incorrect line format");
   |                       --------------------- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

Yet (from some reason I still don't know), when I run the code below it works completely fine:

let line = String::from("something=random");
let mut splitted_line = line.split("=");
let key = splitted_line.nth(0).expect("incorrect line format");
let value = splitted_line.nth(1).expect("incorrect line format");

As far as I read from the Error code description . This shouldn't have happened cause I'm not borrowing any value from a variable.

Can someone explain to me why the first code raises the temporary value error and why the second one doesn't?

split() is borrowing. It takes &self and returns an iterator that yields &str s referencing self .

The difference between the codes is when the splitted string is freed: in the first snippet it is a temporary because we invoke a method on it immediately and it is freed at the end of the statement ( let mut splitted_line = String::from("something=random").split("="); ). However, since we use the strings split() returned after, and they're borrowing from this freed string, this is an error.

On the second case, the string is not temporary as it is bound to a variable, and it is freed at the end of the scope. Thus, it is still alive when we use split() returned strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM