gpt4 book ai didi

filter - 为什么我的迭代器过滤器中针对泛型类型的比较操作不起作用?

转载 作者:行者123 更新时间:2023-11-29 07:50:28 24 4
gpt4 key购买 nike

我试图理解为什么以下代码无法编译(Playground):

fn inspection<I>(iter: I)
where
I: Iterator,
I::Item: Ord,
{
let inspection = iter
.filter(|x| x > 0);
}

fn main() {
let data = vec![1, 2, 3];
inspection(data.iter()); // or inspection(data.into_iter());
}

错误是:

error[E0308]: mismatched types
--> src/main.rs:9:25
|
9 | .filter(|x| x > 0);
| ^ expected reference, found integral variable
|
= note: expected type `&<I as std::iter::Iterator>::Item`
found type `{integer}`

我尝试遵循各种替代方案(通过取消引用元素),如 here 所述没有成功。

第一次尝试:

.filter(|x| **x > 0); 
error[E0614]: type `<I as std::iter::Iterator>::Item` cannot be dereferenced
--> src/main.rs:13:21
|
13 | .filter(|x| **x > 0);
|

第二次尝试:

.filter(|&x| *x > 0);
error[E0614]: type `<I as std::iter::Iterator>::Item` cannot be dereferenced
--> src/main.rs:13:22
|
13 | .filter(|&x| *x > 0);
|

为什么程序编译不通过?

最佳答案

最大的问题(另一个问题已由 Lukas 解决)是您将迭代器的通用项与整数进行比较,而 PartialOrd/Ord 提供的比较仅有效相同类型之间:

pub trait Ord: Eq + PartialOrd<Self> {
fn cmp(&self, other: &Self) -> Ordering;
...
}

为了使类型 T 与数字(在本例中为 0)进行比较,T 必须是数字并且 0 也需要是 T 类型。包含有用数字特征的 num crate 可以用它的 Zero 帮助这里提供通用 0 的特征:

extern crate num;

use num::Zero;

fn inspection<'a, I, T: 'a>(iter: I)
where
I: Iterator<Item = &'a T>,
T: Zero + PartialOrd // T is an ordered number
{
let inspection = iter.filter(|&x| *x > T::zero()); // T::zero() is 0 of the same type as T
}

fn main() {
let data = vec![1, 2, 3];
inspection(data.iter());
}

关于filter - 为什么我的迭代器过滤器中针对泛型类型的比较操作不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51223080/

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