【发布时间】:2019-09-06 15:10:00
【问题描述】:
我想创建具有默认类型的通用结构。但是 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而不让用户为泛型类型而烦恼,你应该使用构建器模式。 -
这里的编译器无法确定 T 的类型是默认类型,因为它试图从正确的部分推断类型。你可以用这个简单的提示来帮助它:` let c:C = C { t: None };`