作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下代码:
pub trait Iterx: Iterator {
fn zip_map<U, T, F>(self, other: U, f: F) -> Map<Zip<Self, U::IntoIter>, F>
where
Self: Sized,
U: IntoIterator,
F: Fn((<Self as Iterator>::Item, <U as IntoIterator>::Item)) -> T,
{
self.zip(other.into_iter()).map(f) // |(x, y)| f(x, y))
}
}
可以按如下方式使用:
#[test]
fn test_zip_map() {
assert_equal((1..5).zip_map(1..5, |(a, b)| a + b), vec![2, 4, 6, 8]);
assert_equal((1..5).zip_map(1..5, |(a, b)| a * b), vec![1, 4, 9, 16]);
}
但是,我希望它能够像这样使用:
#[test]
fn test_zip_map() {
assert_equal((1..5).zip_map(1..5, |a, b| a + b), vec![2, 4, 6, 8]);
assert_equal((1..5).zip_map(1..5, |a, b| a * b), vec![1, 4, 9, 16]);
^^^^^^
no parentheses
}
有谁知道如何修改 zip_map
来实现这个?
谢谢!
最佳答案
不幸的是,因为我们不能命名闭包的名称,也不能使用 impl Fn...
作为 map 第二个泛型我们必须使用 Box
ed 特征对象。
use std::iter::Map;
use std::iter::Zip;
pub trait Iterx: Iterator {
fn zip_map<U, T, F>(
self,
other: U,
f: F,
) -> Map<
Zip<Self, U::IntoIter>,
Box<dyn Fn((<Self as Iterator>::Item, <U as IntoIterator>::Item)) -> T>,
>
where
Self: Sized,
U: IntoIterator,
F: Fn(<Self as Iterator>::Item, <U as IntoIterator>::Item) -> T + 'static,
{
self.zip(other.into_iter()).map(Box::new(move |(x, y)| f(x, y)))
}
}
impl<I> Iterx for I where I: Iterator {}
#[test]
fn test_zip_map() {
assert_eq!(
(1..5)
.into_iter()
.zip_map(1..5, |a, b| a + b)
.collect::<Vec<_>>(),
vec![2, 4, 6, 8]
);
}
关于rust - 如何使 Rust 函数 `zip_map` 采用二元函数而不是以二元组作为参数的一元函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74609203/
我有以下代码: pub trait Iterx: Iterator { fn zip_map(self, other: U, f: F) -> Map, F> where
我是一名优秀的程序员,十分优秀!