我正在Rust中使用递归枚举。我有以下代码:
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
}
当我尝试编译时会抛出:
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
为什么我要为G
参数提供类型,因为Rdd::Data
枚举不需要它?我该如何解决这个问题?
提前感谢
编译器需要知道所有通用参数,因为您可以将值更新为Rdd::Map
,因此它想知道其大小。
在这种情况下,我将使用虚拟的默认通用参数创建自己的构造函数:
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);
}
注意,您无法用所需的任何rdd_1
更新Map
。