I’m a new user of Rust and I am following the experimental book to learn it. I have read this chapter: https://rust-book.cs.brown.edu/ch04-04-slices.html, where they propose the following code:
fn first_word(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
My doubt is about &item, they say:
"Because we get a reference to the element from .iter().enumerate(), we use & in the pattern."
If that’s the case, then why do they use item like item == b' '. From my understanding, if item is a reference, then I would need to access the value the reference is pointing to, something like *item == b' '.
Could someone explain to me the difference? Sorry if it’s a trivial question.
>Solution :
b' ' is a u8. It’s not a reference, just an ordinary, everyday scalar. Without any dereferences, if we write
for (i, item) in bytes.iter().enumerate() {
then item is a &u8, since we’re borrowing from the underlying iterator. We can’t compare a &u8 to a u8, so we need to deref. We can deref at the call site
if *item == b' '
or in the pattern
for (i, &item) in bytes.iter().enumerate()
but not both. It’s your call how you deref, but you have to get rid of the reference somehow.