繁体   English   中英

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

[英]Returning References from Struct Method with Lifetimes

我正在尝试这个代码:

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();

}

现在,据我所知, byte_1是从字节借来的。 但是它的寿命已经过了。 仍然当我编译这个时,我看到以下错误:

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

这里的第一个可变借用是什么? 当 byte_1 超出范围时不应该释放它吗?

重要的是,我应该怎么做才能解决这个问题?

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

现在,当您说fn next(&'a mut self) -> Option<&'a mut u8> { ,您正在重用相同的'a ,并且您说它与返回的可变引用相同。 您是说返回的生命周期与ByteIter结构内容相同。

删除额外的生命周期约束,编译器将可以自由计算适当的生命周期:

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