I’m reading the rust book, which gave me the following code:
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> MyBox<T> {
MyBox(x)
}
}
Since I prefer using Self
, I changed it to:
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> Self<T> {
Self(x)
}
}
However, the compiler complains that:
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> {
| ~~~~~
I know I can fix it by changing Self
to MyBox
, but why does the compiler complain in the first place? If the compiler is already smart enough to figure out that “Self
is on type MyBox
in this impl
“, then why does it reject my code?
Self
already includes the type parameters, so there it means MyBox<T>
, not MyBox
, so Self<T>
is being rejected for the same reason that MyBox<T><T>
would be. Just write Self
, with no <T>
:
struct MyBox<T>(T);
impl<T> MyBox<T> {
fn new(x: T) -> Self {
Self(x)
}
}
1