templates - 为什么我不能让构造函数在显式定义另一个类型参数的同时推导出一个类型参数?

标签 templates generics constructor rust

为什么我不能让构造函数在像这样显式定义另一个类型参数的同时推导出一个类型参数(其中 AB 应该是不同的)?

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/

相关文章:

java - 在对父类(super class)构造函数的 super 调用中使用子类方法作为参数

c++ - 存储任何(但恒定)长度的 std::arrays 集

iOS 8 Metal 模板坏了

templates - 从模板返回动态 AliasSeq

c# - Mock 的通用方法(Moq 库)验证从未使用任何参数组合调用方法

android - Kotlin 上限 : What difference does `:Any` make to Kotlin's generic type inference?

c++ - 静态 constexpr 变量与函数

泛型:类型应该对另一种类型进行操作,而是对声明的文字值进行操作?

java - 在类构造函数中将对象保存到数据库是一种不好的做法吗?

javascript - 通过 this 在 typescript 中从派生类型调用构造函数