1

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

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you soy much! It works. Unfortunatelly as you say, I cannot use any map function, I'll read about GADT in Rust. I don't understand why G is equal to () and then you use the where, but I will finish the book and I hope the explanation is there. Thank you again
new_data creates an Rdd with dummy parameters G and H: that's why I wrote that this solution is useful only when you won't user the Map variant after that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.