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()
,
mut
change a growable string?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: