Mutable references

Hi, i'm begginer and my inglish is very bad, so sorry. My code:

fn consume(rd: &mut BufReader<File>) -> bool {
    match rd.fill_buf() {
        Ok(buf) => {
            rd.consume(buf.len());
            true
        },
        Err(err) => false,
    }
}

The error:

cannot borrow *rd as mutable more than once at a time

¿rd.fill_buf and rd.consume aren't the same rd mutable reference?

Thanks

Try this

fn consume(rd: &mut BufReader<File>) -> bool {
    match rd.fill_buf() {
        Ok(buf) => {
            let len = buf.len();
            rd.consume(len);
            true
        },
        Err(err) => false,
    }
}

I don't get it but it works.
Perfect. Thank you very much alice.

buf is returned from rd.fill_buf(), and points to inside rd, so it is the same reference.

Then rd.consume wants to borrow rd again, but can't, because buf-from-rd is still borrowed. The compiler will borrow rd.consume first, then evaluate buf.len(), then call it.

When you move len = buf.len() a line earlier, then borrow of buf can end before call to rd.consume.

1 Like

Ok, Kornel,
I appreciate your explanation
Thank you very mach.
Do you know if there is a rust book for dummies?. I need one.

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.