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 in mutable variable

  • mut

  • The variable can be made mutable using mut. Then it can be replaced, but the literal (hard-coded) string is baked into the code of the program and thus it cannot be changed runtime.

  • This is an str type.

fn main() {
    let mut name = "Foo";
    let other = name;
    println!("{name}");
    println!("{other}");

    name = "Foo Bar";

    //name.push_str(" Bar");

    println!("{name}");
    println!("{other}");
}
Foo
Foo
Foo Bar
Foo
error[E0599]: no method named `push_str` found for reference `&str` in the current scope
 --> examples/ownership/literal_string_in_mutable_variable.rs:9:10
  |
9 |     name.push_str(" Bar");
  |          ^^^^^^^^ method not found in `&str`

error: aborting due to previous error

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