这个问题在这里已经有了答案:
What's the difference between placing "mut" before a variable name and after the ":"?
(3 个回答)
1年前关闭。
我正在阅读 Rust 文档,在那里我读到了 slices .根据页面的文本,切片是不可变的引用:
This is also why string literals are immutable; &str is an immutable reference.
我希望下面的代码中有两件事:
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]
}
最佳答案
yetnewstring
的类型是 &str
,只有绑定(bind)是可变的。分配是有效的,因为您正在分配另一个 &str
值为 &str
变量,这很好。
关于rust - 切片中的不可变引用是如何更新的?为什么它不改变引用变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63578971/