[英]Why does Rust require generic type declarations after the “impl” keyword?
Defining the methods of generic type requires adding generic types after impl
: 定义泛型类型的方法需要在
impl
之后添加泛型类型:
struct GenericVal<T>(T,);
impl <T> GenericVal<T> {}
I feel that removing <T>
seems OK: 我觉得删除
<T>
似乎没问题:
struct GenericVal<T>(T,);
impl GenericVal<T> {}
Is it any special consideration? 有什么特别的考虑吗?
Rust allows you to write impl
blocks that apply only to some specific combination of type parameters. Rust允许您编写仅适用于某些特定类型参数组合的
impl
块。 For example: 例如:
struct GenericVal<T>(T);
impl GenericVal<u32> {
fn foo(&self) {
// method foo() is only defined when T = u32
}
}
Here, the type GenericVal
is generic, but the impl
itself is not. 这里,
GenericVal
类型是通用的,但impl
本身不是。
Thus, if you want to write an impl
block that applies for all GenericVal<T>
types, you must first declare a type parameter on the impl
itself (otherwise, T
would try to look up a type named T
). 因此,如果要编写适用于所有
GenericVal<T>
类型的impl
块,则必须首先在impl
本身上声明一个类型参数(否则, T
将尝试查找名为T
的类型)。
struct GenericVal<T>(T);
impl<T> GenericVal<T> {
fn foo(&self) {
// method foo() is always present
}
}
This declaration also lets you have a single type parameter that can be used multiple times, forcing the types to be the same. 此声明还允许您具有可以多次使用的单个类型参数,从而强制类型相同。
struct GenericVal<T, U>(T, U);
impl<V> GenericVal<V, V> {
fn foo(&self) {
// method foo() is only defined when T = U
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.