4

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
  • 388,571
  • 95
  • 1,107
  • 1,366
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233
  • 1
    This reminds me of [another recent question on `str` and their size](https://stackoverflow.com/q/54673145/1233251). – E_net4 Feb 24 '19 at 19:27

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
  • 388,571
  • 95
  • 1,107
  • 1,366