简体   繁体   English

从具有生命周期的结构方法中返回引用

[英]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.现在,据我所知, byte_1是从字节借来的。 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?当 byte_1 超出范围时不应该释放它吗?

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.使用impl<'a> ByteIter<'a> ,您可以声明'a是结构中使用的生命周期,即它是底层切片的生命周期。

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.现在,当您说fn next(&'a mut self) -> Option<&'a mut u8> { ,您正在重用相同的'a ,并且您说它与返回的可变引用相同。 You're saying that the returned lifetime is the same than the ByteIter struct content.您是说返回的生命周期与ByteIter结构内容相同。

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)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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