【问题标题】:How did an immutable reference in a slice get updated? Why doesn't it change the referenced variable's value? [duplicate]切片中的不可变引用是如何更新的?为什么它不改变引用变量的值? [复制]
【发布时间】: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 和他们的(现在是独家的)车不受影响。

标签: rust slice


【解决方案1】:

yetnewstring 的类型是&str,只有 binding 是可变的。该赋值是有效的,因为您将另一个 &str 值分配给 &str 变量,这非常好。

【讨论】:

  • 如果绑定是可变的,这意味着它在这种情况下编辑 newstring2 的值?那么最后的打印语句不应该输出“westtheSlice”吗?
  • 它没有修改newstring2。您正在修改 yetnewstring 以引用字符串文字,而不是 newstring2 的一部分。换句话说,您正在更改 newstring2 指向的内容,而不是其值。
猜你喜欢
  • 2014-11-15
  • 1970-01-01
  • 2015-08-23
  • 2021-03-07
  • 2015-12-13
  • 2012-04-22
  • 2011-06-01
  • 1970-01-01
相关资源
最近更新 更多