Rusty Tip: A String manages its own memory, but a string slice does not.
Key Point: |
---|
The difference between a String type and a str type can be confusing; you should call a String a string, and a str a string slice. Remember that you can modify a string, but you cannot modify a string slice. |
In the Rust programming language, a String
is a data structure
(a struct) that manages its own memory. In fact, a String
is
really just some convenience functions that operate on a
Vec<u8>
.
Suppose I create a new String
:
The memory for the String
(which is
actually a Vec<u8>
) is
valid for the scope in which it is created. As soon as we leave
this scope, then the memory goes away. This lets us modify the String
in place, with code like this:
Some useful methods to know for the String
type are:
String::new()
String::with_capacity(size)
String::clear()
String::push_str(str)
String::len()
String::from(str)
Documentation for the String type can be found in the Rust Standard Library documentation.
Be careful not to confuse the String
type with the
primitive type called str
,
or a string slice.
A str
is zero or more contiguous UTF-8 characters.
The difference between a String
type and a str
type can be confusing;
you should call a String
a string, and a str
a string slice.
Remember that you can modify a string, but you cannot modify a string slice.
In the code below, the characters in the str
(string slice) are in the source code, and so get
compiled into the binary.
In this example, my_str
is a string slice that points somewhere in
memory, and you cannot modify it. A String
can be changed (if it stays in scope),
but a str
(string slice) is immutable and cannot be changed.
You can experiment with Rust at the Rust playground.