【问题标题】:Comparing iterator with (fixed sized) array将迭代器与(固定大小的)数组进行比较
【发布时间】:2016-09-09 17:14:07
【问题描述】:

我构建了一个生成无限素数列表的迭代器。类型如下所示:

pub struct Primes { … }

impl Iterator for Primes {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item> { … }
}

现在我想通过比较来测试我的迭代器是否返回正确的值 前 100 个值与正确值对比:

#[test]
fn first_thousand() {
    assert_eq!(
        Primes::new().take(100),
        first_100_primes
    );
}

const first_100_primes: [u32; 100] = [2, 3, …, 541];

我不知道如何比较这些值。我尝试创建一个切片 (first_100_primes[..]),收集迭代器值,但我似乎无法比较它们。

【问题讨论】:

标签: iterator rust infinite


【解决方案1】:

事实证明我真的很接近,我相信这是可行的:

#[test]
fn first_thousand() {
    assert_eq!(
        FIRST_100_PRIMES[..],
        Primes::new().take(100).collect::<Vec<_>>()[..]
    );
}

(虽然我不确定这是否是 rustacean 的做法......)

【讨论】:

  • 我更喜欢副本上的答案,所以我想我会使用那个:)
【解决方案2】:
let is_correct = Primes::new()
    .zip(FIRST_100_PRIMES.iter())
    .all(|(a, &b)| a == b);
assert!(is_correct);

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2022-10-23
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多