Roshan Perera
Roshan Perera

Reputation: 1

Why can I declare a str variable as mutable if Rust str is immutable?

According to: https://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/book/first-edition/strings.html

rust str is immutable, and cannot be used when mutability is required.

However, the following program compiles and works

fn main() {
    let mut mystr = "foo";   
    mystr = "bar";    
    {
         mystr = "baz";      
    }
    println!("{:?}", mystr);  
}

Can someone explain the mutability of str in Rust?

I expect let mut mystr = "foo"; to result in compilation error since str in Rust is immutable. But it compiles.

Upvotes: 0

Views: 300

Answers (1)

Miiao
Miiao

Reputation: 998

You did not change the string itself. &str is basically (*const u8, usize) - a pointer to the buffer and a length. While mutating a variable with type &str, you’re just replacing one pointer with another and not mutating the original buffer. Immutability of a string literal means that the buffer is actually linked to your binary (and, as I remember, is contained in .rodata), so you cannot change it’s contents. To actually mutate a string, use a heap-allocated one - String.

Upvotes: 2

Related Questions