Strings
The way Rust works with strings differs a bit from strings in other languages. All strings are valid sequences of Unicode (UTF8) bytes. They can contain null bytes, but they are not null terminated as in C.
Rust distinguishes two types of string:
- The strings we have used until now are string slices, whose type is
&str
. The&
points out that a string slice is a reference to a string. They are immutable and have a fixed size. For example, the following bindings declare string slices:
// from Chapter 4/code/strings.rs let magician1 = "Merlin"; let greeting = "Hello, world!";
- Or if we explicitly annotate the string variable with its type:
let magician2: &str = "Gandalf";
- We can also define it as a string literal:
let magician2: &'static str = "Gandalf";
- The
&'static
denotes that the string is statically allocated, and stored directly in the executable program. When declaring global constants, indicating the type is mandatory, but for a let binding...