我希望创建一个具有默认类型的通用结构。但是Rust编译器仍然要求我在创建结构时指定明确的类型。
struct A {}
struct C<T = A> {
t: Option<T>
}
fn main() {
let c = C { t: None };
}
Rust编译器显示以下错误:
error[E0282]: type annotations needed for `C<T>`
--> src/main.rs:8:9
|
8 | let c = C { t: None };
| - ^ cannot infer type for `T`
| |
| consider giving `c` the explicit type `C<T>`, where the type parameter `T` is specified
如何允许我的代码用户省略泛型参数?
struct
而不让用户受到通用类型的干扰,你应该使用构建器模式。 - Boiethioslet c:C = C { t: None };
- Denys Séguret