我需要一个函数,该函数可以接受每个泛型类型的一些参数,并且能够将操作应用于单个参数。
我当前无法正常工作的测试尝试:
pub fn gen_test<I>(f: fn(I) -> f32) -> f32
where
I:IntoIterator+Default,
<I as IntoIterator>::Item: Add
{
let start = I::default();
let plus_one: I = start.into_iter().map(|p|p+p).collect();
let value:f32 = f(plus_one);
return value;
}
沿着I
的思路思考是一种结构,其中包含可能不同类型的多个值,并在它们之上实现了一些迭代器。例如:
#[derive(Default)]
struct SomeStruct {
x: u32,
y: f32
}
// I'm not sure how to implement an iterator across differing types
fn some_function(SomeStruct some_struct) -> f32 {
(some_struct.x as f32 + some_struct.y)
}
fn main() {
let value = gen_test(some_function);
}
在这里collect
时,我得到了错误:a value of type
I
cannot be built from an iterator over elements of type<<I as IntoIterator>::Item as Add>::Output
value of typeI
cannot be built fromstd::iter::Iterator<Item=<<I as IntoIterator>::Item as Add>::Output>
我怎样才能解决这个问题?
最佳答案
听起来您至少需要2个不同的泛型类型参数,因为I
可以充当一些T
的容器,可以对其进行迭代或从中进行收集,在这种情况下,我们可以使用以下界限:
use std::iter::FromIterator;
use std::ops::Add;
pub fn gen_test<I, T>(f: fn(I) -> f32) -> f32
where
I: IntoIterator<Item = T> + Default + FromIterator<T>,
T: Add<Output = T> + Copy,
{
let start = I::default();
let plus_one: I = start.into_iter().map(|p| p + p).collect();
let value: f32 = f(plus_one);
value
}
playground
关于function - 无法从通用元素的迭代器构建通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65646935/