Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I need to use & in this code example

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."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading