【问题标题】:How do I write a custom `IntoIterator` implementation that simply reverses the iteration?如何编写简单地反转迭代的自定义“IntoIterator”实现?
【发布时间】:2021-07-21 13:38:27
【问题描述】:

我是 Rust 新手,我正在尝试实现具有 Vec 的自定义 struct。我希望这个自定义结构是可迭代的,并且以相反的顺序在内部 Vec 上进行迭代。

到目前为止,我的理解是,我需要实现 IntoIterator 特征,并最终实现自定义 Iterator,IntoIterator 将自定义结构转换为该 Iterator。由于我只想在Vec 上反转迭代,因此我正在考虑重新使用标准库已经提供的内容。

这是我的结构:

pub struct BitMap {
    content: Vec<u64>,
}

这就是我尝试实现IntoIterator的方式:

impl<'a> iter::IntoIterator for &'a BitMap {
    type Item = u64;
    type IntoIter = iter::Rev<slice::Iter<'a, Self::Item>>;

    fn into_iter(self) -> Self::IntoIter {
        (&(self.content)).iter().rev()
    }
}

但是编译器抱怨:

47  |     type IntoIter = iter::Rev<slice::Iter<'a, Self::Item>>;
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u64`, found reference

我很难理解如何实现这个简单的事情。

更新

感谢E_net4 says don't copy that您的answer!

考虑到您提到您的解决方案需要复制元素,我尝试实现一个版本来避免它,这就是我想出的:

impl<'a> iter::IntoIterator for &'a BitMap {
    type Item = u64;
    type IntoIter = BitMapIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        BitMapIterator::new(&self.content)
    }
}

pub struct BitMapIterator<'a> {
    content: &'a Vec<u64>,
    index: usize,
}

impl<'a> BitMapIterator<'a> {
    fn new(content: &'a Vec<u64>) -> Self {
        BitMapIterator {
            content,
            index: content.len(),
        }
    }
}

impl iter::Iterator for BitMapIterator<'_> {
    type Item = u64;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index == 0 {
            None
        } else {
            self.index -= 1;
            Some(self.content[self.index])
        }
    }
}

但正如您所见,这还需要我实现一个自定义迭代器并将其公开。这似乎符合我的要求,如果我在不复制元素的情况下理解正确,但我不知道这个解决方案有多惯用,它基本上不会重用 std lib 提供的任何东西。

【问题讨论】:

  • 请避免building up follow-up questions on the same post。不过,您可能误解了复制适配器的作用,因此我编辑了答案。它不会急切地复制结构体,因此不需要分配任何额外的内存。
  • 你说得对,抱歉后续跟进。感谢您提及copy 所做的事情并指出它并不急于求成。另一方面,我是否正确假设我在更新中发布的 sn-p 完全避免了复制?尽管复制u64 的成本很低,但我正在考虑Vec 的大小可能很大的情况,例如2^64。
  • 从你做self.content[self.index]的那一刻起仍然有一个副本。该语法将隐式取消引用向量中的该位置,这仍然需要一个副本,因为值不能从借位中移出。相关问题:stackoverflow.com/questions/27904864stackoverflow.com/questions/51344641 我想说你的实现不太可能带来任何性能或效率的提升。

标签: rust iterator traits


【解决方案1】:

在向量上调用.iter() 会创建一个非拥有项的迭代器,该迭代器将位于不可变引用的后面。而&amp;u64 items 的迭代器并不能起到u64 items 的迭代器的作用。

考虑到u64 的复制成本很低,使用.copied 调整迭代器就足以获得返回实际值的迭代器。复制的迭代器是惰性的,它只在遍历项目时复制它们。

use std::{iter, slice};

pub struct BitMap {
    content: Vec<u64>,
}

impl<'a> iter::IntoIterator for &'a BitMap {
    type Item = u64;
    type IntoIter = iter::Copied<iter::Rev<slice::Iter<'a, Self::Item>>>;

    fn into_iter(self) -> Self::IntoIter {
        self.content.iter().rev().copied()
    }
}

Playground

另见:

【讨论】:

  • 由于into_iter 使用结构并且向量归结构所有(即它也被使用),因此只使用self.content.into_iter() 并调整关联类型以使用vec::IntoIter 可能是合适的.
  • 这将是一种可能的实现,@Cerberus,但完全不同。这一点尤其与它不消耗完整结构,只消耗对它的引用的特征相一致。
  • 啊。抱歉,错过了迭代的是&amp;BitMap,而不是BitMap。
猜你喜欢
  • 2017-08-22
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 2011-04-04
  • 2013-12-10
相关资源
最近更新 更多