Rust中为何Self类型不允许添加类型参数?
Rust中使用
Self<T>为何触发编译错误? 我正在阅读《Rust编程入门》,书中给出的代码如下:
struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> MyBox<T> { MyBox(x) } }
因为偏好使用Self,我把代码修改成了这样:
struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> Self<T> { Self(x) } }
但编译器抛出了错误:
error[E0109]: type arguments are not allowed on self type --> src/main.rs:64:26 | 64 | fn new(x: T) -> Self<T> { | ---- ^ type argument not allowed | | | not allowed on self type | note: `Self` is of type `MyBox<T>` --> src/main.rs:61:8 | 61 | struct MyBox<T>(T); | ^^^^^ `Self` corresponds to this type 62 | 63 | impl<T> MyBox<T> { | ---------------- `Self` is on type `MyBox` in this `impl` help: the `Self` type doesn't accept type parameters, use the concrete type's name `MyBox` instead if you want to specify its type parameters | 64 | fn new(x: T) -> MyBox<T> { | ~~~~~
我知道把Self<T>改成MyBox<T>能修复问题,但疑惑的是:编译器明明已经识别出当前impl块中Self对应MyBox<T>,为什么还是会拒绝我的代码?
解答
在Rust的impl<T> MyBox<T>块中,Self是已经绑定了当前泛型参数的完整类型别名,它直接等价于MyBox<T>,不是需要填充泛型参数的“类型模板”。
语法规则上,Self不允许附加任何类型参数——因为它已经是“实例化”后的具体类型,就像你不能写MyBox<T><T>一样,Self<T>本身就是错误的写法。
编译器虽然清楚Self对应MyBox<T>,但它会严格遵循语法规则:Self在当前impl块里是带泛型参数的最终类型,不需要也不能再添加参数。如果想保持Self的使用习惯,直接去掉<T>即可:
struct MyBox<T>(T); impl<T> MyBox<T> { fn new(x: T) -> Self { Self(x) } }
这样既符合你的偏好,也能正常通过编译。
内容的提问来源于stack exchange,提问作者PRO
相关产品推荐
相关产品推荐

