首页 > 解决方案 > Rust:在`impl`中的函数中返回对成员变量的引用

问题描述

如何确定返回成员变量引用的函数的生命周期?只要结构处于活动状态,该引用就有效。

这是一个可能需要的示例:

struct CountUpIter<'a, T> {
    output: &'a mut T,
}

fn next<'a, T>(selff: &'a mut CountUpIter<'a, T>) -> Option<&'a T> {
    Some(&selff.output)
}

// This does not work
// first, the lifetime cannot outlive the lifetime '_ as defined on the impl so that reference does not outlive borrowed content
// but, the lifetime must be valid for the lifetime 'a as defined on the impl
impl<'a, T> Iterator for CountUpIter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        Some(&self.output)
    }
}

// Neither does this. It fails with the same error
impl<'a, T> Iterator for &mut CountUpIter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<Self::Item> {
        Some(&self.output)
    }
}

我已经尽可能多地匹配了这个问题&T的解决方案,但我不想迭代Vec<&T>

标签: rustlifetimeborrow-checker

解决方案


推荐阅读