]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/strings.md
9be019783b0f5f77af0bc5b29b98b09698a097be
[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 a valid
11 encoding of UTF-8 sequences. Additionally, unlike some systems languages,
12 strings are not null-terminated and can contain null bytes.
13
14 Rust has two main types of strings: `&str` and `String`. Let’s talk about
15 `&str` first. These are called ‘string slices’. A string slice has a fixed
16 size, and cannot be mutated. It is a reference to a sequence of UTF-8 bytes.
17
18 ```rust
19 let greeting = "Hello there."; // greeting: &'static str
20 ```
21
22 `"Hello there."` is a string literal and its type is `&'static str`. String
23 literal is a string slice that is statically allocated, meaning that it’s saved
24 inside our compiled program, and exists for the entire duration it runs. The
25 `greeting` binding is a reference to this statically allocated string.
26
27 String literals can span multiple lines. There are two forms. The first will
28 include the newline and the leading spaces:
29
30 ```rust
31 let s = "foo
32     bar";
33
34 assert_eq!("foo\n        bar", s);
35 ```
36
37 The second, with a `\`, does not trim the spaces:
38
39 ```rust
40 let s = "foo\
41     bar"; 
42
43 assert_eq!("foobar", s);
44 ```
45
46 Rust has more than just `&str`s though. A `String`, is a heap-allocated string.
47 This string is growable, and is also guaranteed to be UTF-8. `String`s are
48 commonly created by converting from a string slice using the `to_string`
49 method.
50
51 ```rust
52 let mut s = "Hello".to_string(); // mut s: String
53 println!("{}", s);
54
55 s.push_str(", world.");
56 println!("{}", s);
57 ```
58
59 `String`s will coerce into `&str` with an `&`:
60
61 ```rust
62 fn takes_slice(slice: &str) {
63     println!("Got: {}", slice);
64 }
65
66 fn main() {
67     let s = "Hello".to_string();
68     takes_slice(&s);
69 }
70 ```
71
72 This coercion does not happen for functions that accept one of `&str`’s traits
73 instead of `&str`. For example, [`TcpStream::connect`][connect] has a parameter
74 of type `ToSocketAddrs`. A `&str` is okay but a `String` must be explicitly
75 converted using `&*`.
76
77 ```rust,no_run
78 use std::net::TcpStream;
79
80 TcpStream::connect("192.168.0.1:3000"); // &str parameter
81
82 let addr_string = "192.168.0.1:3000".to_string();
83 TcpStream::connect(&*addr_string); // convert addr_string to &str
84 ```
85
86 Viewing a `String` as a `&str` is cheap, but converting the `&str` to a
87 `String` involves allocating memory. No reason to do that unless you have to!
88
89 ## Indexing
90
91 Because strings are valid UTF-8, strings do not support indexing:
92
93 ```rust,ignore
94 let s = "hello";
95
96 println!("The first letter of s is {}", s[0]); // ERROR!!!
97 ```
98
99 Usually, access to a vector with `[]` is very fast. But, because each character
100 in a UTF-8 encoded string can be multiple bytes, you have to walk over the
101 string to find the nᵗʰ letter of a string. This is a significantly more
102 expensive operation, and we don’t want to be misleading. Furthermore, ‘letter’
103 isn’t something defined in Unicode, exactly. We can choose to look at a string as
104 individual bytes, or as codepoints:
105
106 ```rust
107 let hachiko = "忠犬ハチ公";
108
109 for b in hachiko.as_bytes() {
110     print!("{}, ", b);
111 }
112
113 println!("");
114
115 for c in hachiko.chars() {
116     print!("{}, ", c);
117 }
118
119 println!("");
120 ```
121
122 This prints:
123
124 ```text
125 229, 191, 160, 231, 138, 172, 227, 131, 143, 227, 131, 129, 229, 133, 172,
126 忠, 犬, ハ, チ, 公,
127 ```
128
129 As you can see, there are more bytes than `char`s.
130
131 You can get something similar to an index like this:
132
133 ```rust
134 # let hachiko = "忠犬ハチ公";
135 let dog = hachiko.chars().nth(1); // kinda like hachiko[1]
136 ```
137
138 This emphasizes that we have to walk from the beginning of the list of `chars`.
139
140 ## Slicing
141
142 You can get a slice of a string with slicing syntax:
143
144 ```rust
145 let dog = "hachiko";
146 let hachi = &dog[0..5];
147 ```
148
149 But note that these are _byte_ offsets, not _character_ offsets. So
150 this will fail at runtime:
151
152 ```rust,should_panic
153 let dog = "忠犬ハチ公";
154 let hachi = &dog[0..2];
155 ```
156
157 with this error:
158
159 ```text
160 thread '<main>' panicked at 'index 0 and/or 2 in `忠犬ハチ公` do not lie on
161 character boundary'
162 ```
163
164 ## Concatenation
165
166 If you have a `String`, you can concatenate a `&str` to the end of it:
167
168 ```rust
169 let hello = "Hello ".to_string();
170 let world = "world!";
171
172 let hello_world = hello + world;
173 ```
174
175 But if you have two `String`s, you need an `&`:
176
177 ```rust
178 let hello = "Hello ".to_string();
179 let world = "world!".to_string();
180
181 let hello_world = hello + &world;
182 ```
183
184 This is because `&String` can automatically coerce to a `&str`. This is a
185 feature called ‘[`Deref` coercions][dc]’.
186
187 [dc]: deref-coercions.html
188 [connect]: ../std/net/struct.TcpStream.html#method.connect