【发布时间】:2020-12-14 03:39:20
【问题描述】:
我正在阅读 Rust 文档,在那里我读到了 slices。根据页面的文本,切片是不可变的引用:
这也是字符串字面量不可变的原因; &str 是不可变的引用。
我希望下面的代码中有两件事:
-
yetnewstring = "we";给出编译时错误 - 即使我对上述内容有误,我仍然希望
newstring2的最后一个打印语句的输出为westtheSlice。
下面的代码是如何工作的?
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]
}
【问题讨论】:
-
谢谢,帖子中的答案非常有用。所以是的,
*s = String::from("testtheSlice");cahnges :“你好”到“testtheSlice”。但我对代码的其余部分感到困惑。yetnewstring = test123(&mut newstring2);从newstring2获得的价值如何?此外,如果yetnewstring是一个引用&str类型的可变变量,是否意味着它可以更改它所引用的&str持有的值?如果是的话,为什么在我们将yetnewstring的值更新为“我们”之后,这种情况下newstring2的值会发生变化? -
除此之外,
&str不是字符串文字。字符串字面量是&str(特别是&'static str),但除此之外还有很多方法可以创建&str,它只是对存在于某处的字符串数据的非拥有引用。 -
" 另外,如果 Yetnewstring 是一个可变变量,引用 &str 类型,是否意味着它可以改变 &str 所引用的值?"不,您可以将它所指的内容更改为其他内容,但您不能更改其所指内容的内容。
-
"为什么在我们将 Yetnewstring 的值更新为 "we" 之后,在这种情况下 dint newstring2 的值会发生变化?"因为您刚刚更改了
yetnewstring指向的内容。newstring2独立指向同一个地方,但您没有(也不能)更改指针。 -
这样想:Harold 和 Kumar 都有车。这是同一辆车,他们共享。 Kumar 得到了一辆新车,Kumar 的车与以前不同,但改变的是 Kumar,而不是车本身,所以 Harold 和他们的(现在是独家的)车不受影响。