rust - 为什么 std::iter::Map 不能作为迭代器返回- ?
问题描述
我想将此行的映射部分变成一个函数:
let i: Vec<u32> = (0..=5).map(|x| x * 2).collect();
我编写了这段代码,我认为这将是我从原始代码中删除的内容的插入:
let j: Vec<u32> = process(0..=5).collect();
fn process<I>(src: I) -> I
where
I: Iterator<Item = u32>,
{
src.map(|x| x * 2)
}
我得到这个编译时错误:
error[E0308]: mismatched types
--> src/lib.rs:5:5
|
1 | fn process<I>(src: I) -> I
| - - expected `I` because of return type
| |
| this type parameter
...
5 | src.map(|x| x * 2)
| ^^^^^^^^^^^^^^^^^^ expected type parameter `I`, found struct `std::iter::Map`
|
= note: expected type parameter `I`
found struct `std::iter::Map<I, [closure@src/lib.rs:5:13: 5:22]>`
既然std::iter::Map<u32, u32>
实现了Iterator
特征,它不应该能够返回Iterator<Item = u32>
吗?
我能够使它与以下内容一起工作:
fn process<I>(src: I) -> std::iter::Map<I, Box<dyn Fn(u32) -> u32>>
where
I: Iterator<Item = u32>,
{
src.map(Box::new(|x| x * 2))
}
这涉及将闭包包装在Box
. 有没有更好或更简洁的方法来匹配内联函数?
解决方案
推荐阅读
- mysql - MySQL 工作台 - 覆盖 tlsVersion
- scala - 生菜 6.0.1.RELEASE 已弃用 .withPassword
- javascript - 如何为材料选择器实现默认工具栏以进行反应?
- flutter - Flutter:单击按钮时重新加载 SplashScreen
- pandas - 如何将 NBA-API 列表转换为 DataFrame
- c# - 尝试在 Visual Studio 上的 Xamarin iOS 应用程序中使用 System.Data.SqlClient 库连接 SQL Server 时出错
- spring-boot - 有没有办法在spring boot中禁用重定向并将http状态发送为302
- javascript - 如何在 DIV 中使用串联字符串?
- c# - 依赖注入:如何将从方法参数接收到的值集成到我想要解析为构造函数参数的依赖项中?
- amazon-web-services - 2 同一子网 AWS 中的微服务