来自未实现TrustedLen的迭代器的TrustedLen迭代器

jpfvwuh4  于 2023-02-04  发布在  其他
关注(0)|答案(1)|浏览(105)

我刚接触Rust,所以这可能是一个天真的问题,但我在研究TrustedLen特性时感到困惑。它描述了一个TrustedLen迭代器“报告一个大小提示,其中它要么是精确的(下限等于上限),要么是上限为None。”我对我们从另一个没有实现TrustedLen的迭代器创建TrustedLen迭代器的情况很好奇。

pub fn main() -> () {
    let v = vec![1, 2, 3, 4, 5];
    
    let (lower, upper) = v.iter().filter(|num| {*num % 2 == 0}).take(2).size_hint();
    println!("({},{})", lower, upper.unwrap());
}

这将生成以下消息

(0,2)

这里的下限与上限不匹配,因为过滤器 predicate ,但是我在实现TrustedLen的Take迭代器上调用size_hint。

ygya80vv

ygya80vv1#

Take只有在内部迭代器为TrustedLen时才有条件地实现TrustedLen。在这种情况下,Filter不是,因此迭代器不是TrustedLen

#![feature(trusted_len)]

fn require_trusted_len(_: impl std::iter::TrustedLen) {}

fn main() {
    let v = vec![1, 2, 3, 4, 5];
    
    let iter = v.iter().filter(|num| {*num % 2 == 0}).take(2);
    require_trusted_len(iter);
}

Yields

error[E0277]: the trait bound `Filter<std::slice::Iter<'_, {integer}>, [closure@src/main.rs:8:32: 8:37]>: TrustedLen` is not satisfied
 --> src/main.rs:9:25
  |
9 |     require_trusted_len(iter);
  |     ------------------- ^^^^ the trait `TrustedLen` is not implemented for `Filter<std::slice::Iter<'_, {integer}>, [closure@src/main.rs:8:32: 8:37]>`
  |     |
  |     required by a bound introduced by this call
  |
  = help: the following other types implement trait `TrustedLen`:
            &mut I
            ArrayChunksMut<'_, T, N>
            Chunks<'_, T>
            ChunksExact<'_, T>
            ChunksExactMut<'_, T>
            ChunksMut<'_, T>
            Cloned<I>
            Copied<I>
          and 44 others
  = note: required for `std::iter::Take<Filter<std::slice::Iter<'_, {integer}>, [closure@src/main.rs:8:32: 8:37]>>` to implement `TrustedLen`
note: required by a bound in `require_trusted_len`
 --> src/main.rs:3:32
  |
3 | fn require_trusted_len(_: impl std::iter::TrustedLen) {}
  |                                ^^^^^^^^^^^^^^^^^^^^^ required by this bound in `require_trusted_len`

相关问题