我正在使用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枚举不需要它?我怎样才能解决这个问题?
提前感谢
发布于 2019-12-02 15:36:26
编译器需要知道所有的泛型参数,因为您可以将值更新为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。
https://stackoverflow.com/questions/59141825
复制相似问题