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

标签 rust slice

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





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/

    相关文章:

    arrays - 从字节 slice 中提取位到一个 int slice 中

    Go:(运算符 + 未在 slice 上定义)

    rust - Rust类型别名导致生命周期问题

    c - 如何处理将 usize 传递给需要 uint32_t 的 C 函数?

    generics - 使用动态和静态调度为特征实现者实现功能

    python - 在 Python 中对系列进行切片和索引

    go - 为什么golang slice初始化后为空?

    rust - Higher Ranked Trait Bound 和盒装闭包生命周期问题

    rust - 如何为相似的匹配武器编写宏?

    python - 在二维 Numpy 数组中切片非连续索引