How pattern maching works in for loop vars binding

fn first_word(s: &String) -> usize {
    let mut x = s.as_bytes();

    for (i, &item) in x.iter().enumerate() {
        //  item = 4;
        if item == b' ' {
            return i;


fn main() {}


In above code why &item?

The type that the iterator returns is (usize, &u8), so the pattern means i is usize and item is a u8. Note how the & line up, so the binding of item "sees through" the reference, if you will.

This is how pattern bindings work generally, not something for loop specific.


I like this metaphor. but it seems that ref/ref mut is an exception , which does not match anything. it behaves more like an action : turn whatever type of the target into a borrow/mutable borrow.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.