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 really mutable string

If we would like to have a string that can really be change we need to make sure or code will allocate some space in the memory where we can really change things.

For this Rust provides a type called String.

In this example we take a literal string which is going to be embedded in the binary and using the String::from function we create a copy of the string in an area of the memory (in the heap) that we can actually change. We also need to mark the variable to be mutable using the mut keyword if we really want to change it.

The push_str method will append another string to the one we have.

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

    name.push_str(" Bar");
    println!("{name}");
}

Output:

Foo
Foo Bar

  • String
  • from
  • push_str