rust - 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>
。
解决方案
推荐阅读
- shell - 从 Array-Shell 脚本中提取和匹配多个值
- grep - 如何在 grep 中指示与当前目录不同的搜索目录
- spring-batch - 是否可以在知道外部作业(执行)ID 的情况下访问 JobParameters?
- git - Git快速前进到上游而无需结帐
- c# - TFS 持续集成 clickonce 应用程序
- python - 使用 django 应用程序运行 gunicorn 的各种问题
- php - 如何在循环中用树枝对值求和?
- java - Spring JPA 特性,允许跨不同实体重用单个 Repo 方法
- javascript - 使用网格显示时如何正确定位css帖子项目
- python - 在熊猫折线图中绘制多列