[英]Can not infer type of generic function in recursive enums in Rust
我正在 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);
}
請注意,您無法使用您想要的任何Map
更新您的rdd_1
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.