简体   繁体   中英

Returning References from Struct Method with Lifetimes

I am trying this code:

struct ByteIter<'a> {
    remainder: &'a mut [u8],
    index: usize,
}

impl<'a> ByteIter<'a> {
    fn new(remainder: &'a mut [u8]) -> ByteIter<'a> {
        ByteIter{remainder, index: 0}
    }

    fn next(&'a mut self) -> Option<&'a mut u8> {
        if self.index >= self.remainder.len() {
            None
        } else {
            let mut byte = &mut self.remainder[self.index];
            self.index  += 1;
            Some(byte)
        }
    }
}

fn main() {
    let mut a = [ 0x51, 0x52, 0x53, 0x54];
    let mut bytes = ByteIter::new(&mut a);
    {
        let byte_1 = bytes.next();
    }
    let byte_2 = bytes.next();

}

Now, as I understand, the byte_1 was borrowed from bytes. But it's lifetime has already expired. Still when I compile this, I see the following error:

29 |     let byte_2 = bytes.next();
   |                  ^^^^^
   |                  |
   |                  second mutable borrow occurs here
   |                  first borrow later used here

What is the first mutable borrow here? Shouldn't it be released when byte_1 goes out of scope?

Importantly, what should I do to fix this?

With impl<'a> ByteIter<'a> , you declare that 'a is the lifetime used in the structure, ie, it's the lifetime of the underlying slice.

Now, when you say fn next(&'a mut self) -> Option<&'a mut u8> { , you're reusing the same 'a , and you say it's the same than the returned mutable reference. You're saying that the returned lifetime is the same than the ByteIter struct content.

Remove the additional lifetime constraint and the compiler will be free to compute the appropriate lifetime:

fn next(& mut self) -> Option<& mut u8> {
    if self.index >= self.remainder.len() {
        None
    } else {
        let mut byte = &mut self.remainder[self.index];
        self.index  += 1;
        Some(byte)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM