Skip to content

Commit 2e2e1a1

Browse files
committed
Rearrange explanatory text and code to make sense
Fixes #350.
1 parent 212ff12 commit 2e2e1a1

File tree

1 file changed

+13
-12
lines changed

1 file changed

+13
-12
lines changed

src/ch04-03-slices.md

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,15 +45,15 @@ the `String` argument
4545
</figcaption>
4646
</figure>
4747

48-
Let’s break down this code a bit:
48+
Let’s break down this code a bit. Because we need to go through the `String`
49+
element by element and check whether a value is a space, we’ll convert our
50+
`String` to an array of bytes using the `as_bytes` method:
4951

5052
```rust,ignore
5153
let bytes = s.as_bytes();
5254
```
5355

54-
Because we need to go through the `String` element by element and check whether
55-
a value is a space, we’ll convert our `String` to an array of bytes using the
56-
`as_bytes` method:
56+
Next, we create an iterator over the array of bytes using the `iter` method :
5757

5858
```rust,ignore
5959
for (i, &item) in bytes.iter().enumerate() {
@@ -66,10 +66,15 @@ first element of the returned tuple is the index, and the second element is a
6666
reference to the element. This is a bit more convenient than calculating the
6767
index ourselves.
6868

69-
Because the method returns a tuple, we can use patterns, just like everywhere
70-
else in Rust. So we match against the tuple with `i` for the index and `&item`
71-
for a single byte. Because we get a reference from `.iter().enumerate()`, we
72-
use `&` in the pattern:
69+
Because the `enumerate` method returns a tuple, we can use patterns to
70+
destructure that tuple, just like everywhere else in Rust. So in the `for`
71+
loop, we specify a pattern that has `i` for the index in the tuple and `&item`
72+
for the single byte in the tuple. Because we get a reference to the element
73+
from `.iter().enumerate()`, we use `&` in the pattern.
74+
75+
We search for the byte that represents the space by using the byte literal
76+
syntax. If we find a space, we return the position. Otherwise, we return the
77+
length of the string by using `s.len()`:
7378

7479
```rust,ignore
7580
if item == b' ' {
@@ -79,10 +84,6 @@ use `&` in the pattern:
7984
s.len()
8085
```
8186

82-
We search for the byte that represents the space by using the byte literal
83-
syntax. If we find a space, we return the position. Otherwise, we return the
84-
length of the string by using `s.len()`.
85-
8687
We now have a way to find out the index of the end of the first word in the
8788
string, but there’s a problem. We’re returning a `usize` on its own, but it’s
8889
only a meaningful number in the context of the `&String`. In other words,

0 commit comments

Comments
 (0)