与特征迭代器类型不匹配作为函数参数

Type mismatch with iterator of traits as function argument

我有一个函数接受特征作为参数包装在 Box

use std::fmt::Display;

fn push(e: Box<dyn Display>) {}

push(Box::new(0));

现在我想创建另一个接受迭代器的函数,其中每个项目都是相同类型

fn push_batch<I>(batch: I)
where
    I: IntoIterator<Item = Box<dyn Display>>,
{
}

push_batch((0..10).map(|i| Box::new(i)));

但是这样做会导致以下错误:

error[E0271]: type mismatch resolving `<[closure@src/main.rs:13:28: 13:43] as FnOnce<({integer},)>>::Output == Box<(dyn std::fmt::Display + 'static)>`
  --> src/main.rs:13:5
   |
5  | fn push_batch<I>(batch: I)
   |    ---------- required by a bound in this
6  | where
7  |     I: IntoIterator<Item = Box<dyn Display>>,
   |                     ----------------------- required by this bound in `push_batch`
...
13 |     push_batch((0..10).map(|i| Box::new(i)));
   |     ^^^^^^^^^^ expected integer, found trait object `dyn std::fmt::Display`
   |
   = note: expected struct `Box<{integer}>`
              found struct `Box<(dyn std::fmt::Display + 'static)>`
   = note: required because of the requirements on the impl of `Iterator` for `Map<std::ops::Range<{integer}>, [closure@src/main.rs:13:28: 13:43]>`

为什么第一个示例可以编译而第二个示例不能?我如何创建一个盒装特征的迭代器以传递给 push_batch 函数?

Rust 不会自动将 Box<T> 转换为 Box<dyn Trait>,您必须明确地这样做:

push_batch((0..10).map(|i| Box::new(i) as Box<dyn Display>));