gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:42:50 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com