generics - 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
解决方案
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.
推荐阅读
- python - Python简化包含OR和AND的if条件
- sql-server - 在 WHERE 子句中添加条件会产生更多结果
- symfony - 实体在更改后不更新
- hibernate - 使用通用生成器时出错
- java - WebDriverWait 在 Selenium 4 中已弃用
- javascript - 如何将每个循环变量值推入数组
- javascript - JSON。JAVA 和 PHP 检查表单值是否存在
- solr - SOLR - 从给定搜索请求的相交多边形中获取所有文档条目
- java - 不是一个文件中的 JSON 对象异常,但不同的 json 文件有效
- postgresql - Symfony 4 + Api 平台无法自动验证类型为“NULL”的值。在 nativeSQL 查询上