3 Strings are an important concept for any programmer to master. Rust's string
4 handling system is a bit different from other languages, due to its systems
5 focus. Any time you have a data structure of variable size, things can get
6 tricky, and strings are a re-sizable data structure. That being said, Rust's
7 strings also work differently than in some other systems languages, such as C.
9 Let's dig into the details. A *string* is a sequence of Unicode scalar values
10 encoded as a stream of UTF-8 bytes. All strings are guaranteed to be
11 validly encoded UTF-8 sequences. Additionally, strings are not null-terminated
12 and can contain null bytes.
14 Rust has two main types of strings: `&str` and `String`.
16 The first kind is a `&str`. These are called *string slices*. String literals
17 are of the type `&str`:
20 let string = "Hello there."; // string: &str
23 This string is statically allocated, meaning that it's saved inside our
24 compiled program, and exists for the entire duration it runs. The `string`
25 binding is a reference to this statically allocated string. String slices
26 have a fixed size, and cannot be mutated.
28 A `String`, on the other hand, is an in-memory string. This string is
29 growable, and is also guaranteed to be UTF-8.
32 let mut s = "Hello".to_string(); // mut s: String
35 s.push_str(", world.");
39 You can get a `&str` view into a `String` with the `as_slice()` method:
42 fn takes_slice(slice: &str) {
43 println!("Got: {}", slice);
47 let s = "Hello".to_string();
48 takes_slice(s.as_slice());
52 To compare a String to a constant string, prefer `as_slice()`...
55 fn compare(string: String) {
56 if string.as_slice() == "Hello" {
62 ... over `to_string()`:
65 fn compare(string: String) {
66 if string == "Hello".to_string() {
72 Viewing a `String` as a `&str` is cheap, but converting the `&str` to a
73 `String` involves allocating memory. No reason to do that unless you have to!
75 That's the basics of strings in Rust! They're probably a bit more complicated
76 than you are used to, if you come from a scripting language, but when the
77 low-level details matter, they really matter. Just remember that `String`s
78 allocate memory and control their data, while `&str`s are a reference to
79 another string, and you'll be all set.