likes
comments
collection
share

为什么 Rust 中 impl 后面的泛型要写两次?

作者站长头像
站长
· 阅读数 15

原文:Why do we need to write the generic types after the impl keyword?

提问:

impl<T> SomeGenericStruct<T> {
    ...
}

我不明白为什么这里的 要写两次。

四年前 Rusky 回答道:

这两处泛型参数并不总是一样,你可以在添加约束

impl<T: Display> SomeGenericStruct<T> {
    fn can_assume_display(&self) { .. }
}

而且两处的参数个数也可能不一样,比如

impl SomeGenericStruct<i32> { .. }

再比如:

struct Pair<A, B> {
    first: A,
    second: B,
}

impl<T> Pair<i32, T> {
    fn first_argument_is_i32(&self) { .. }
}

不过,当两处的泛型参数完全一致时,写两次确实很烦,确实应该得到简化。

Morgan 回答道:

第一个 T 是声明,第二个 T 是使用。

如果不先声明,那么 Rust 就不能确定 T 是泛型还是具体类型,示例如下:

struct Foo<T> {
    x: T
}

impl<T> Foo<T> {
    fn new() -> Foo<T> {
        unimplemented!()
    }
}

type T = i32;

impl Foo<T> { // 你能确定 T 是泛型还是 i32 吗?
    fn new_t() -> Foo<T> {
        unimplemented!()
    }
}

我比较喜欢后面这个答案。

完。