Literal strings in variables are immutable
Similar to numbers, if we declare a variable and assign a string to it as in the following example, that variable is going to be immutable.
fn main() { let text = "Hello World!"; println!("{text}"); text = "Something else"; println!("{text}"); }
We get the following compilation error:
error[E0384]: cannot assign twice to immutable variable `text`
--> src/main.rs:5:5
|
2 | let text = "Hello World!";
| ----
| |
| first assignment to `text`
| help: consider making this binding mutable: `mut text`
...
5 | text = "Something else";
| ^^^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
For more information about this error, try `rustc --explain E0384`.
error: could not compile `immutable-string` (bin "immutable-string") due to 1 previous error
What happens if we make the variable mutable?