Skip to content

Commit 68f8122

Browse files
committed
Auto merge of #29846 - JanLikar:#29823, r=steveklabnik
Fix #29823 by further explaining `&str` and pointing out the difference between `&str` and `&'static str`.
2 parents 768630b + 8bcbcae commit 68f8122

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

src/doc/trpl/strings.md

+8-7
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,18 @@ encoding of UTF-8 sequences. Additionally, unlike some systems languages,
1212
strings are not null-terminated and can contain null bytes.
1313

1414
Rust has two main types of strings: `&str` and `String`. Let’s talk about
15-
`&str` first. These are called ‘string slices’. String literals are of the type
16-
`&'static str`:
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.
1717

1818
```rust
1919
let greeting = "Hello there."; // greeting: &'static str
2020
```
2121

22-
This string is statically allocated, meaning that it’s saved inside our
23-
compiled program, and exists for the entire duration it runs. The `greeting`
24-
binding is a reference to this statically allocated string. String slices
25-
have a fixed size, and cannot be mutated.
22+
`"Hello there."` is a string literal and its type is `&'static str`. A 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. Any
26+
function expecting a string slice will also accept a string literal.
2627

2728
String literals can span multiple lines. There are two forms. The first will
2829
include the newline and the leading spaces:
@@ -34,7 +35,7 @@ let s = "foo
3435
assert_eq!("foo\n bar", s);
3536
```
3637

37-
The second, with a `\`, does not trim the spaces:
38+
The second, with a `\`, trims the spaces and the newline:
3839

3940
```rust
4041
let s = "foo\

0 commit comments

Comments
 (0)