返回借用数据迭代器时如何修复Rust生命周期问题?
Rust音频缓冲区crate的可变视图生命周期问题
我正在开发一个抽象音频缓冲区的Rust crate,非连续切片是核心挑战。我的解决方案是使用MutableView结构体,它通过映射函数将连续索引重映射为非连续索引。
这个crate的核心是Buffer trait,它允许沿着BufferAxis trait定义的轴对缓冲区进行索引。缓冲区的帧/通道实现了BufferAxis,对于非连续的帧/通道,具体类型为View或MutableView。我现在需要为MutableView实现BufferAxisMut trait,代码如下:
impl<'a, D, M, J> BufferAxisMut<D::Output> for MutableView<'a, D, M, usize, J> where D: IndexMut<J>, M: InjectiveMapper<usize, J>, D::Output: 'a, { fn get_sample_mut(&mut self, index: usize) -> Option<&mut D::Output> { self.get_mut(index) } fn iter_samples_mut<'this>(&'this mut self) -> impl Iterator<Item = &'this mut D::Output> where D::Output: 'this, { MutableViewIterMut { // lifetime may not live long enough view: self, // consider adding the following bound: `'this: 'a` index: 0, } } }
这段代码触发了以下编译错误:
lifetime may not live long enough consider adding the following bound: `'this: 'a`
完整的错误日志如下:
Compiling playground v0.0.1 (/playground) error: lifetime may not live long enough --> src/lib.rs:191:9 | 177 | impl<'a, D, M, J> BufferAxisMut<D::Output> for MutableView<'a, D, M, usize, J> | -- lifetime `'a` defined here ... 187 | fn iter_samples_mut<'this>(&'this mut self) -> impl Iterator<Item = &'this mut D::Output> | ----- lifetime `'this` defined here ... 191 | / MutableViewIterMut { 192 | | view: self, 193 | | index: 0, 194 | | } | |_________^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'this` | = help: consider adding the following bound: `'this: 'a` error: could not compile `playground` (lib) due to 1 previous error
我有几个疑问和需求:
- 编译器建议的
'this: 'a约束无法应用——这个约束不在trait的签名中,而且'a是MutableView特有的生命周期,没法加到trait签名里。 - 另外,
'this: 'a意味着'this的生命周期要长于'a,但'this是结构体实例的生命周期,而结构体本身就带有'a,这难道不是理所当然的吗? - 现在无法应用这个建议,是不是我的实现模式本身存在问题?
我需要解决这个生命周期问题,同时想了解这是不是Rust中的常见模式,有没有实现这类非连续可变视图迭代的通用模式,以及相关的解释或学习资源。
内容的提问来源于stack exchange,提问作者Pizza98
相关产品推荐
相关产品推荐

