泛型类型不能从泛型元素上的迭代器构建

Generic type cannot be built from iterator over generic elements

我需要一个函数,它可以接受一定数量的每个泛型参数,并能够对单个参数应用操作。

我当前的失败测试尝试:

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 type I cannot be built from std::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