@@ -45,15 +45,15 @@ the `String` argument
45
45
</figcaption >
46
46
</figure >
47
47
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:
49
51
50
52
``` rust,ignore
51
53
let bytes = s.as_bytes();
52
54
```
53
55
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 :
57
57
58
58
``` rust,ignore
59
59
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
66
66
reference to the element. This is a bit more convenient than calculating the
67
67
index ourselves.
68
68
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() ` :
73
78
74
79
``` rust,ignore
75
80
if item == b' ' {
@@ -79,10 +84,6 @@ use `&` in the pattern:
79
84
s.len()
80
85
```
81
86
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
-
86
87
We now have a way to find out the index of the end of the first word in the
87
88
string, but there’s a problem. We’re returning a ` usize ` on its own, but it’s
88
89
only a meaningful number in the context of the ` &String ` . In other words,
0 commit comments