简体   繁体   中英

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

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.

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);
}

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