gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:36:38 24 4
gpt4 key购买 nike

我有一个函数,将一个特征作为参数包装在Box

use std::fmt::Display;

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

push(Box::new(0));
现在,我想创建另一个函数,该函数接受一个迭代器,其中每个Item都是相同的类型
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>));

关于rust - 类型不匹配与特征迭代器作为函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65050617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com