为什么我不能让构造函数在像这样显式定义另一个类型参数的同时推导出一个类型参数(其中 A
和 B
应该是不同的)?
struct S<A, B: Default> {
a: A, b: B
}
impl<A, B: Default> S<A, B> {
fn new<B>(a: A) -> Self {
S {
a: a,
b: Default::default(),
}
}
}
fn main() {
let s = S::new::<u32>(10);
}
这给出了一个错误:
error[E0194]: type parameter `B` shadows another type parameter of the same name
--> test.rs:6:12
|
5 | impl<A, B: Default> S<A, B> {
| - first `B` declared here
6 | fn new<B>(a: A) -> Self {
| ^ shadows another type parameter
可以重命名内部参数 ( fn new<B1>
),但在尝试使用构造函数时会发生错误:
error[E0282]: type annotations needed
--> test.rs:15:13
|
15 | let s = S::new::<u32>(10);
| - ^^^^^^^^^^^^^ cannot infer type for `B`
| |
| consider giving `s` a type
如果fn new
在没有任何额外参数的情况下声明,可以按如下方式创建对象,但这会强制指定两个模板化参数 IIUC:
let s = S::<i32, u32>::new(10);
最佳答案
我认为您根本不想在函数上指定类型参数。相反,您应该只允许编译器在构造结构时使用 _
作为类型来推断结构的其他类型参数:
struct S<A, B: Default> {
a: A, b: B
}
impl<A, B: Default> S<A, B> {
fn new(a: A) -> Self {
S {
a: a,
b: Default::default(),
}
}
}
fn main() {
let s = S::<_, u32>::new(10);
}
关于templates - 为什么我不能让构造函数在显式定义另一个类型参数的同时推导出一个类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44634463/