Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Literal string

  • The variable "name" points to a literal string. (aka. hard-coded string). The string can never change.
  • Because the variable is not mutable, we cannot even replace the content. (See error message generated by the commented out code.)
fn main() {
    let name = "Foo";
    let other = name;
    println!("{name}");
    println!("{other}");

    //name = "Foo Bar";

    println!("{name}");
    println!("{other}");
}
Foo
Foo
Foo
Foo
error[E0384]: cannot assign twice to immutable variable `name`
 --> examples/ownership/literal_string.rs:7:5
  |
2 |     let name = "Foo";
  |         ----
  |         |
  |         first assignment to `name`
  |         help: consider making this binding mutable: `mut name`
...
7 |     name = "Foo Bar";
  |     ^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable

error: aborting due to previous error

For more information about this error, try `rustc --explain E0384`.