It is important to note that the related item is mentioned in the error message. enum Foo { Baz } has no related items. A trait can have an associated element:
trait FooBaz { type Baz } // ^~~~~~~~ - associated item
To summarize:
Why not use Self in this situation?
Due to this problem . RFC 2338 has not yet been implemented .
It seems that Self acts as a type alias, albeit with some modifications.
Where exactly can I use Self ?
The self can only be used in traits and impl . This code:
struct X { f: i32, x: &Self, }
Outputs the following:
error[E0411]: cannot find type 'Self' in this scope --> src/main.rs:3:9 | 3 | x: &Self, | ^^^^ 'Self' is only available in traits and impls
Perhaps this is a temporary situation and may change in the future!
More precisely, Self should be used only as part of the method signature (for example, fn self_in_self_out(&self) → Self ) or to access a related type:
enum Foo { Baz, } trait FooBaz { type Baz; fn b(&self) -> Self::Baz; // Valid use of 'Self' as method argument and method output } impl FooBaz for Foo { type Baz = Foo; fn b(&self) -> Self::Baz { let x = Foo::Baz as Self::Baz; // You can use associated type, but it just a type x } }
I think user4815162342 covered the rest of the answer best .
Daniel Fath
source share