I was going through the Rust documentation where I read about slices. As per the page's text, a slice is an immutable reference:
This is also why string literals are immutable; &str is an immutable reference.
I would expect 2 things in below code:
yetnewstring = "we";
to give a compile time error- Even if I'm wrong about the above, I still expect the output of the last print statement for
newstring2
to bewesttheSlice
.
How does the below code work?
fn main() {
let mut newstring2: String; //declare new mutable string
newstring2 = String::from("Hello"); // add a value to it
println!("this is new newstring: {}", newstring2); // output = Hello
let mut yetnewstring = test123(&mut newstring2); // pass a mutable reference of newstring2 , and get back a string literal
println!("this is yetnewstring :{}", yetnewstring); // output = "te"
yetnewstring = "we"; // how come this is mutable now ? arent string literals immutable?
println!("this is the Changed yetnewstring :{}", yetnewstring); // output = "we"
println!("this is newstring2 after change of yetnewstring = 'we' : {}" , newstring2); // output = "testtheSlice"
// if string literal yetnewstring was reference to a slice of newstring2 ,
//then shouldnt above output have to be :"westtheSlice"
}
fn test123(s: &mut String) -> &str {
*s = String::from("testtheSlice");
&s[0..2]
}