Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

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.

like image 699
MR SIR Avatar asked Aug 01 '26 05:08

MR SIR


1 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.

like image 90
Angelicos Phosphoros Avatar answered Aug 02 '26 21:08

Angelicos Phosphoros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!