1 % The Guide to Rust Strings
3 Strings are an important concept to master in any programming language. If you
4 come from a managed language background, you may be surprised at the complexity
5 of string handling in a systems programming language. Efficient access and
6 allocation of memory for a dynamically sized structure involves a lot of
7 details. Luckily, Rust has lots of tools to help us here.
9 A **string** is a sequence of unicode scalar values encoded as a stream of
10 UTF-8 bytes. All strings are guaranteed to be validly-encoded UTF-8 sequences.
11 Additionally, strings are not null-terminated and can contain null bytes.
13 Rust has two main types of strings: `&str` and `String`.
17 The first kind is a `&str`. This is pronounced a 'string slice'.
18 String literals are of the type `&str`:
21 let string = "Hello there.";
24 Like any Rust type, string slices have an associated lifetime. A string literal
25 is a `&'static str`. A string slice can be written without an explicit
26 lifetime in many cases, such as in function arguments. In these cases the
27 lifetime will be inferred:
30 fn takes_slice(slice: &str) {
31 println!("Got: {}", slice);
35 Like vector slices, string slices are simply a pointer plus a length. This
36 means that they're a 'view' into an already-allocated string, such as a
37 `&'static str` or a `String`.
41 A `String` is a heap-allocated string. This string is growable, and is also
42 guaranteed to be UTF-8.
45 let mut s = "Hello".to_string();
48 s.push_str(", world.");
52 You can coerce a `String` into a `&str` with the `as_slice()` method:
55 fn takes_slice(slice: &str) {
56 println!("Got: {}", slice);
60 let s = "Hello".to_string();
61 takes_slice(s.as_slice());
65 You can also get a `&str` from a stack-allocated array of bytes:
70 let x: &[u8] = &[b'a', b'b'];
71 let stack_str: &str = str::from_utf8(x).unwrap();
76 ## `String` vs. `&str`
78 In general, you should prefer `String` when you need ownership, and `&str` when
79 you just need to borrow a string. This is very similar to using `Vec<T>` vs. `&[T]`,
80 and `T` vs `&T` in general.
82 This means starting off with this:
88 and only moving to this:
94 If you have good reason. It's not polite to hold on to ownership you don't
95 need, and it can make your lifetimes more complex.
99 To write a function that's generic over types of strings, use `&str`.
102 fn some_string_length(x: &str) -> uint {
107 let s = "Hello, world";
109 println!("{}", some_string_length(s));
111 let s = "Hello, world".to_string();
113 println!("{}", some_string_length(s.as_slice()));
117 Both of these lines will print `12`.
121 To compare a String to a constant string, prefer `as_slice()`...
124 fn compare(x: String) {
125 if x.as_slice() == "Hello" {
131 ... over `to_string()`:
134 fn compare(x: String) {
135 if x == "Hello".to_string() {
141 Converting a `String` to a `&str` is cheap, but converting the `&str` to a
142 `String` involves an allocation.
146 You may be tempted to try to access a certain character of a `String`, like
150 let s = "hello".to_string();
152 println!("{}", s[0]);
155 This does not compile. This is on purpose. In the world of UTF-8, direct
156 indexing is basically never what you want to do. The reason is that each
157 character can be a variable number of bytes. This means that you have to iterate
158 through the characters anyway, which is a O(n) operation.
160 There's 3 basic levels of unicode (and its encodings):
162 - code units, the underlying data type used to store everything
163 - code points/unicode scalar values (char)
164 - graphemes (visible characters)
166 Rust provides iterators for each of these situations:
168 - `.bytes()` will iterate over the underlying bytes
169 - `.chars()` will iterate over the code points
170 - `.graphemes()` will iterate over each grapheme
172 Usually, the `graphemes()` method on `&str` is what you want:
175 let s = "u͔n͈̰̎i̙̮͚̦c͚̉o̼̩̰͗d͔̆̓ͥé";
177 for l in s.graphemes(true) {
194 Note that `l` has the type `&str` here, since a single grapheme can consist of
195 multiple codepoints, so a `char` wouldn't be appropriate.
197 This will print out each visible character in turn, as you'd expect: first "u͔", then
198 "n͈̰̎", etc. If you wanted each individual codepoint of each grapheme, you can use `.chars()`:
201 let s = "u͔n͈̰̎i̙̮͚̦c͚̉o̼̩̰͗d͔̆̓ͥé";
239 You can see how some of them are combining characters, and therefore the output
242 If you want the individual byte representation of each codepoint, you can use
246 let s = "u͔n͈̰̎i̙̮͚̦c͚̉o̼̩̰͗d͔̆̓ͥé";
303 Many more bytes than graphemes!
305 # Other Documentation
307 * [the `&str` API documentation](std/str/index.html)
308 * [the `String` API documentation](std/string/index.html)