3

I'm reading The Rust Programming Language. The docs define a String as "growable":

A UTF-8 encoded, growable string.

I've found that growable is not the same as mutable, but they don't really explain what makes a type "growable".

Given this let mut guess = String::new(),

  1. What does "growable" mean?
  2. How does mut change a growable string?
  3. Is there a non-growable string type?
Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Armeen Harwood
  • 16,621
  • 30
  • 113
  • 222

1 Answers1

5

You are overthinking the wording here; "growable" only means that it can grow. A String that originally allocated 3 bytes to contain "abc" can grow to 6 bytes to contain "abcdef". The memory allocation can become bigger (and smaller). There's no specific Rust typesystem meaning to the word "growable".

Changing the capacity of a String is a specific type of alteration, so you need a mutable String in order to grow the string. You also need a mutable String for other types of alterations that don't involve changing the allocation.

A mutable string slice (&mut str) is a type of string that cannot become longer or shorter but may be changed.

fn example(name: &mut str) {
    name.make_ascii_uppercase()
}

See also:

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159