切片中的不可变引用如何更新?为什么不更改引用变量的值?

问题描述

我正在阅读有关slices的Rust文档。根据页面文字,切片是不可变的引用:

这也是为什么字符串文字不可变的原因。 &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]
} 

解决方法

yetnewstring的类型为&str,只有 binding 是可变的。分配是有效的,因为您正在为&str变量分配另一个&str值,这很好。