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

A literal string cannot be changed

If we go back to the variable that was holding a literal string, you can see that while we could replace the content of the variable there are no methods allowing us to change the string. Eg. push_str does not exist for literal strings.

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

    name.push_str(" Bar");
}

Compilation error:

error[E0599]: no method named `push_str` found for reference `&str` in the current scope
 --> examples/variables/change_literal_string.rs:5:10
  |
5 |     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`.

  • push_str