ฉันกำลังพยายามส่งต่อการอ้างอิงที่ไม่แน่นอนไปยังโครงสร้าง Container
ซึ่งเก็บการอ้างอิงด้วยอายุการใช้งาน 'a
เนื่องจากการอ้างอิงที่ไม่แน่นอนมักจะอยู่ได้ไม่นานเท่ากับตัวคอนเทนเนอร์เองซึ่งอาจเช่น มีอายุการใช้งาน 'static
ในตัวอย่างของฉัน ฉันพยายามให้อายุการใช้งานของมันเองเป็น 'b
ฉันพยายามระบุว่า 'a
สามารถอยู่ได้นานกว่า 'b
ด้วยไวยากรณ์ 'a: 'b
อย่างไรก็ตาม รหัสผลลัพธ์ไม่ได้คอมไพล์พร้อมข้อความแสดงข้อผิดพลาดที่เป็นความลับ
เกิดอะไรขึ้นที่นี่? ฉันจะแก้ไขได้อย่างไร?
นี่คือตัวอย่างการทำงานขั้นต่ำของฉัน:
// Example container with a lifetime
struct Container<'a> {
sequence: &'a [usize],
}
impl<'a> Container<'a> {
// Returns an Iterator which holds a reference to the container to iterate over
fn get_iterator(&mut self) -> ContainerIterator<'a, '_> {
ContainerIterator {
container: self,
index: 0,
}
}
}
// Iterator which holds a reference to the Container where 'b may outlive 'a
struct ContainerIterator<'a, 'b>
where
'b: 'a,
{
container: &'a mut Container<'b>,
index: usize,
}
// Simple iterator implementation as an example
impl<'a, 'b> Iterator for ContainerIterator<'a, 'b> {
type Item = usize;
fn next(&mut self) -> Option<usize> {
if self.index >= self.container.sequence.len() {
None
} else {
Some(self.container.sequence[self.index])
}
}
}
impl<'a, 'b> ExactSizeIterator for ContainerIterator<'a, 'b> {}
// This is the function where things go wrong - it should return an iterator which maps the outputs of the `ContainerIterator`
fn get_iterator<'a, 'b: 'a>(
container: &'a mut Container<'b>,
) -> impl ExactSizeIterator<Item = usize> + 'a {
container.get_iterator().map(|index| index * 2)
}
fn main() {
// Container with 'static data and some example code
let mut container = Container {
sequence: &[1, 2, 3, 4, 5],
};
let output: Vec<_> = get_iterator(&mut container).collect();
dbg! {output};
}
นี่เป็นข้อผิดพลาดของคอมไพเลอร์ที่เกิดขึ้นซึ่งฉันไม่รู้วิธีตีความหรือแก้ไข:
error[E0623]: lifetime mismatch
--> src/main.rs:42:15
|
40 | container: &'a mut Container<'b>,
| ---------------------
| |
| these two types are declared with different lifetimes...
41 | ) -> impl ExactSizeIterator<Item = usize> + 'a {
42 | container.get_iterator().map(|index| index * 2)
| ^^^^^^^^^^^^ ...but data from `container` flows into `container` here
index
ของคุณไม่เคยเพิ่มขึ้น ฉันไม่คิดว่าคุณควรใช้ExactSizeIterator
เพราะคุณไม่ได้ใช้size_hint
- person Shepmaster   schedule 29.09.2020fn get_iterator(&mut self) -> ContainerIterator<'_, 'a>
) เนื่องจากเป็นแบบย้อนหลัง - person Shepmaster   schedule 29.09.2020