0

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.

2
  • 2
    You are not mutating str here, you're just replacing one &str with another &str. Commented Jan 11, 2023 at 21:27
  • 2
    I've never coded rust, but doesn't mut only apply to the variable, not the contents? e.g. you can re-assign the variable to a different string, but you cannot change the string itself? (pretty much like final works in Java). Never coded rust, so I might be totally wrong. Commented Jan 11, 2023 at 21:28

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.