This question is now obsolete because this feature has been implemented. Related answer.
The following Rust code fails to compile:
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Self::Bar
}
}
The error message confuses me:
error[E0599]: no associated item named `Bar` found for type `Foo` in the current scope
--> src/main.rs:7:9
|
7 | Self::Bar
| ^^^^^^^^^
The problem can be fixed by using Foo
instead of Self
, but this strikes me as strange since Self
is supposed to refer to the type that is being implemented (ignoring traits), which in this case is Foo
.
enum Foo {
Bar,
}
impl Foo {
fn f() -> Self {
Foo::Bar
}
}
Why can't Self
be used in this situation? Where exactly can Self
be used*? Is there anything else I can use to avoid repeating the type name in the method body?
* I'm ignoring usage in traits, where Self
refers to whatever type implements the trait.
In Rust, methods cannot only be defined on structs, they can also be defined on tuples and enums, and even on built-in types like integers.
Initializing Enum Variants with Values in Rustlet num = Result::Score(3.14); let bool = Result::Valid(true); Here, we are initializing the enum variants with values inside the bracket. That is, Result::Score(3.14) - initialize the Score variant with the value 3.14.
The size of the enum's values is determined by its largest variant ( One , in your example). Therefore, the values can be stored in the array directly.
This is now possible as of version 1.37.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With