]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/strings.md
Rollup merge of #21357 - kimroen:patch-1, r=sanxiyn
[rust.git] / src / doc / trpl / strings.md
1 % Strings
2
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.
8
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.
13
14 Rust has two main types of strings: `&str` and `String`.
15
16 The first kind is a `&str`. These are called *string slices*. String literals
17 are of the type `&str`:
18
19 ```{rust}
20 let string = "Hello there."; // string: &str
21 ```
22
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.
27
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.
30
31 ```{rust}
32 let mut s = "Hello".to_string(); // mut s: String
33 println!("{}", s);
34
35 s.push_str(", world.");
36 println!("{}", s);
37 ```
38
39 You can get a `&str` view into a `String` with the `as_slice()` method:
40
41 ```{rust}
42 fn takes_slice(slice: &str) {
43     println!("Got: {}", slice);
44 }
45
46 fn main() {
47     let s = "Hello".to_string();
48     takes_slice(s.as_slice());
49 }
50 ```
51
52 To compare a String to a constant string, prefer `as_slice()`...
53
54 ```{rust}
55 fn compare(string: String) {
56     if string.as_slice() == "Hello" {
57         println!("yes");
58     }
59 }
60 ```
61
62 ... over `to_string()`:
63
64 ```{rust}
65 fn compare(string: String) {
66     if string == "Hello".to_string() {
67         println!("yes");
68     }
69 }
70 ```
71
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!
74
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.