0

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.

bython
  • 65
  • 6
  • 1
    Note that `as_bytes()` doesn't return an array, but a _slice_ reference. With a slice, you can only iterate over the references to the thing inside, because you don't own the slice. `&item` is a _pattern_, where `&` doesn't create a reference, it _destructures_ it. You can think of `&` in the pattern as being the _opposite_ of `&` in an expression. And that's not specific to `&`, patterns work like that everywhere. E.g. `if let Some(foo) = bar` doesn't create an option, it destructures it. – user4815162342 Sep 16 '22 at 13:16
  • [This answer](https://stackoverflow.com/a/45197990) contains an excellent explanation to what's happening here. – E_net4 Sep 16 '22 at 13:47
  • I now understand how this works. I haven't read about patterns yet, but I will Thanks for the explanation and recommendation. – bython Sep 16 '22 at 14:53

0 Answers0