【问题标题】:Mutable iterator可变迭代器
【发布时间】:2022-12-16 10:12:47
【问题描述】:

我正在尝试在向量上编写一个可变迭代器,但我无法弄清楚编译器试图告诉我什么。这是我的实现

struct IterMut<'a> {
    vec: &'a mut Vec<u32>,
    index: usize,
}

impl<'a> Iterator for IterMut<'a> {
    type Item = &'a mut u32;

    fn next(&mut self) -> Option<Self::Item> {
        let item = if self.index < self.vec.len() {
            Some(&mut self.vec[self.index])
        } else {
            None
        };

        self.index += 1;

        item
    }
}

编译器错误是:

error: lifetime may not live long enough
  --> src/main.rs:60:9
   |
48 | impl<'a> Iterator for IterMut<'a> {
   |      -- lifetime `'a` defined here
...
51 |     fn next(&mut self) -> Option<Self::Item> {
   |             - let's call the lifetime of this reference `'1`
...
60 |         item
   |         ^^^^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`

非可变版本编译和工作。

struct Iter<'a> {
    vec: &'a Vec<u32>,
    index: usize,
}

impl<'a> Iterator for Iter<'a> {
    type Item = &'a u32;

    fn next(&mut self) -> Option<Self::Item> {
        let item = if self.index < self.vec.len() {
            Some(&self.vec[self.index])
        } else {
            None
        };

        self.index += 1;

        item
    }
}

Here is a playground link with the code to try out.

任何帮助是极大的赞赏。

【问题讨论】:

    标签: rust iterator lifetime


    【解决方案1】:

    问题是你的IterMut 保留了已经传递的元素。 在每晚或一旦take_first_mut稳定下来,你可以这样做:

    #![feature(slice_take)]
    struct IterMut<'a> {
        vec: &'a mut [u32],
    }
    
    impl<'a> Iterator for IterMut<'a> {
        type Item = &'a mut u32;
    
        fn next(&mut self) -> Option<Self::Item> {
            self.vec.take_first_mut()
        }
    }
    

    请注意,我从 &amp;mut Vec&lt;u32&gt; 切换到切片,因为您必须能够“释放”使用 Vec 并不容易的项目

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 1970-01-01
      • 2018-03-06
      • 2011-02-17
      相关资源
      最近更新 更多