我想定义一个函数every,它接受一个迭代器,虽然它不是None,但它确保所有的值都是true。
示例应用程序:
every([true, true, true].into_iter()) == trueevery([true, false, true].into_iter()) == false我很难让它在Vec上工作,更不用说Iterator了。我已经尝试了以下方法和一些变体,但没有取得任何进展。
use std::ops;
fn every<T>(v: Vec<T>) -> bool
where
T: ops::Not,
{
for item in v {
match !item {
T::No => return false,
}
}
true
}下面的代码得到以下错误:
error[E0599]: no associated item named `No` found for type `T` in the current scope
--> src/lib.rs:9:13
|
9 | T::No => return false,
| ^^^^^ associated item not found in `T`发布于 2018-12-29 18:26:42
基于Stargateur's comment的更通用的示例
fn every<T, I>(v: I) -> bool
where
I: IntoIterator<Item = T>,
T: std::ops::Not<Output = bool>,
{
v.into_iter().all(|x| !!x)
}v可以是实现IntoIterator的任何东西,例如Vec,也可以是像map或filter这样的东西,这使得这个解决方案非常通用。
https://stackoverflow.com/questions/53968385
复制相似问题