Git repo: https://github.com/caveofprogramming/rust
Creating Strings
We can create mutable strings of the String
type using any of these three methods:
Adding to Strings
We can add a string to an existing string using push_str()
, or we can add a single character (defined with single quotes) using push()
.
Concatenating Strings
We can also concatenate strings using the plus operator. All strings apart from the first must be references, prefixed with &
.
The first string’s data gets moved to build the result, meaning it’s no longer valid.
Here, s1
cannot be used after the concatenation.
A better way to concatenate strings is by using the format!()
macro.
String Slices
Strings can’t be indexed using a subscript, like [0]
, but we can obtain slices with [x..y]
.
The problem is that the program might crash if you accidentally try to slice on a byte that’s part way through one of the multi-byte unicode characters.
The following works and extracts only the first character, which turns out to occupy two bytes, but changing the slice size can easily result in the program terminating with an error message.
Iterating Over Strings
The correct way to obtain characters from a string is with the chars()
function. The following prints all the characters of the string.