首页 > 解决方案 > Can not infer type of generic function in recursive enums in Rust

问题描述

I'm working with recursive enums in Rust. I have the following code:

enum Rdd<T, G, H>
where
    G: (Fn(&T) -> H),
{
    Data(Vec<T>),
    Map(G, Box<Rdd<T, G, H>>)
}

fn main() {
    let mut v1: Vec<u32> = vec![1, 2, 3, 4, 5, 6];
    let rdd_1 = Rdd::Data(v1); // It does not work
}

When I try to compile It throws:

let rdd_1 = Rdd::Data(v1); // It does not work
^^^^^^^^^ cannot infer type for `G`

consider giving `rdd_1` the explicit type `Rdd<u32, G, H>`, where the type parameter `G` is specified

Why should I provide a type for G parameter as It's not needed for the Rdd::Data enum? How could I solve this problem?

Thanks in advance

标签: genericsfunctional-programmingrusttype-inferencerecursive-datastructures

解决方案


The compiler needs to know all the generic parameters since you could update the value to Rdd::Map, and thus it wants to know its size.

In this situation, I would create my own constructor with dummy default generic parameters:

enum Rdd<T, G = fn(&T) -> (), H = ()>
where
    G: (Fn(&T) -> H),
{
    Data(Vec<T>),
    Map(G, Box<Rdd<T, G, H>>)
}

impl<T> Rdd<T, fn(&T), ()> { // for example
    fn new_data(data: Vec<T>) -> Self {
        Rdd::Data(data)
    }
}

fn main() {
    let mut v1: Vec<u32> = vec![1, 2, 3, 4, 5, 6];
    let rdd_1 = Rdd::new_data(v1);
}

Note that you cannot update your rdd_1 with any Map you want.


推荐阅读