Why do String::from(&str) and &str.to_string() behave differently in Rust?

Viewed 71
fn main() {
   let string = "Rust Programming".to_string();
   let mut slice = &string[5..12].to_string();       // Doesn't work...why?
   let mut slice = string[5..12].to_string();        // works
   let mut slice2 = String::from(&string[5..12]);    // Works

   slice.push('p');
   println!("slice: {}, slice2: {}, string: {}", slice,slice2,string);
}

What is happening here? Please explain.

2 Answers

The main issue here that & have lower priority than method call.

So, actual code is

let mut slice = &(string[5..12].to_string());

So you a taking a reference to temporary String object that dropped and cannot be used later.

You should wrap your reference in parenthesis and call the method on the result.

fn main() {
   let string = "Rust Programming".to_string();
   let mut slice = (&string[5..12]).to_string();     // ! -- this should work -- !
   let mut slice = string[5..12].to_string();        // works
   let mut slice2 = String::from(&string[5..12]);    // Works

   slice.push('p');
   println!("slice: {}, slice2: {}, string: {}", slice,slice2,string);
}
Related