Why borrow an element on a for loop when the element is already a borrowed one

Viewed 33

I am learning rust using the Rust book and also a video course by Let's Get Rusty on youtube which goes through the book chapter by chapter and explains the book. But under this chapter which talks about the slice type I dont understand this code snippet

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()
}

fn main() {}

As I can understand first s.as_bytes() returns a reference of an array of bytes. Now we iterate over the reference of the bytes using a for loop and since we want to use the indices we use enumerate which returns the index which is a type of usize and the element itself which is a reference to the byte(as indicated by the book). So my question did the book use &item on the for loop declaration while already the item is a reference to the byte?

When removing the & from the item the item will be a reference to the byte, but when using the & the type will change to u8 (which is a byte). And that's what confused me I tried to recreate the scenario by doing this

let some_string = String::from("hello");
let &some_var = &some_string;

Which of course will result in an error.

I would absolutely love a thorough explanation.

0 Answers
Related