Skip to content

Commit 3e528b5

Browse files
committed
Fix example for slicing multi-byte characters
1 parent 0e8693c commit 3e528b5

File tree

1 file changed

+17
-12
lines changed

1 file changed

+17
-12
lines changed

cards.md

+17-12
Original file line numberDiff line numberDiff line change
@@ -988,7 +988,7 @@ We **do not** copy the data on the heap that the pointer refers to.
988988
---
989989

990990
```rust
991-
let s1 = String:from("Hello");
991+
let s1 = String::from("Hello");
992992
let s2 = s1;
993993

994994
println!("{}, world!", s1);
@@ -1505,22 +1505,25 @@ If you attempt to create a string slice in the middle of a multi-byte character,
15051505
your program will exit with an error.
15061506

15071507
```rust
1508-
fn first_word(s: &String) -> usize {
1508+
let greeting = "Hello, \u{1F30D}!"; // The globe emoji is a multi-byte character
1509+
let sliced = &greeting[0..9]; // Panics because it's slicing through it
1510+
```
1511+
1512+
---
1513+
1514+
```rust
1515+
fn first_word(s: &String) -> &str {
15091516
let bytes = s.as_bytes();
15101517

15111518
for (i, &item) in bytes.iter().enumerate() {
15121519
if item == b' ' {
1513-
return i;
1520+
return &s[0..i];
15141521
}
15151522
}
15161523

1517-
s.len()
1524+
&s[..]
15181525
}
1519-
```
1520-
1521-
---
15221526

1523-
```rust
15241527
fn main() {
15251528
let mut s = String::from("Hello world");
15261529
let word = first_word(&s);
@@ -1539,12 +1542,14 @@ Compile-time error!
15391542

15401543
If we have an immutable reference to something,
15411544
we cannot also take a mutable reference.
1542-
Because clear needs to truncate the `String`,
1545+
1546+
Because `clear()` needs to truncate the `String`,
15431547
it needs to get a mutable reference.
1544-
The `println!` after the call to clear uses the reference in word,
1548+
The `println!` after the call to `clear()` uses the reference in `word`,
15451549
so the immutable reference must still be active at that point.
1546-
Rust disallows the mutable reference in clear and the immutable
1547-
reference in word from existing at the same time, and compilation fails.
1550+
Rust disallows the mutable reference in `clear()` and the immutable
1551+
reference in `word` from existing at the same time, and compilation fails.
1552+
15481553
Not only has Rust made our API easier to use,
15491554
but it has also eliminated an entire class of errors at compile time!
15501555

0 commit comments

Comments
 (0)