11% The Strings Guide
22
3- # Strings
4-
53Strings are an important concept to master in any programming language. If you
64come from a managed language background, you may be surprised at the complexity
75of string handling in a systems programming language. Efficient access and
@@ -14,7 +12,7 @@ Additionally, strings are not null-terminated and can contain null bytes.
1412
1513Rust has two main types of strings: ` &str ` and ` String ` .
1614
17- ## &str
15+ # &str
1816
1917The first kind is a ` &str ` . This is pronounced a 'string slice.' String literals
2018are of the type ` &str ` :
@@ -38,7 +36,7 @@ Like vector slices, string slices are simply a pointer plus a length. This
3836means that they're a 'view' into an already-allocated string, such as a
3937` &'static str ` or a ` String ` .
4038
41- ## String
39+ # String
4240
4341A ` String ` is a heap-allocated string. This string is growable, and is also
4442guaranteed to be UTF-8.
@@ -73,9 +71,9 @@ let x: &[u8] = &[b'a', b'b'];
7371let stack_str: &str = str::from_utf8(x).unwrap();
7472```
7573
76- ## Best Practices
74+ # Best Practices
7775
78- ### ` String ` vs. ` &str `
76+ ## ` String ` vs. ` &str `
7977
8078In general, you should prefer ` String ` when you need ownership, and ` &str ` when
8179you just need to borrow a string. This is very similar to using ` Vec<T> ` vs. ` &[T] ` ,
@@ -98,7 +96,7 @@ need, and it can make your lifetimes more complex. Furthermore, you can pass
9896either kind of string into ` foo ` by using ` .as_slice() ` on any ` String ` you
9997need to pass in, so the ` &str ` version is more flexible.
10098
101- ### Comparisons
99+ ## Comparisons
102100
103101To compare a String to a constant string, prefer ` as_slice() ` ...
104102
@@ -123,7 +121,7 @@ fn compare(string: String) {
123121Converting a ` String ` to a ` &str ` is cheap, but converting the ` &str ` to a
124122` String ` involves an allocation.
125123
126- ## Other Documentation
124+ # Other Documentation
127125
128126* [ the ` &str ` API documentation] ( /std/str/index.html )
129127* [ the ` String ` API documentation] ( std/string/index.html )
0 commit comments