问题描述
我正在阅读有关slices的Rust文档。根据页面的文字,切片是不可变的引用:
这也是为什么字符串文字不可变的原因。 &str是不可变的引用。
我期望下面的代码有两件事:
以下代码如何工作?
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]
}
解决方法
yetnewstring
的类型为&str
,只有 binding 是可变的。分配是有效的,因为您正在为&str
变量分配另一个&str
值,这很好。