Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't `Self` be used to refer to an enum's variant in a method body?

Tags:

enums

rust

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.

like image 959
Challenger5 Avatar asked Sep 25 '17 02:09

Challenger5


People also ask

Can enums have methods Rust?

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.

How do you initialize an enum in Rust?

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.

How are enums stored in Rust?

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.


1 Answers

This is now possible as of version 1.37.

like image 156
Challenger5 Avatar answered Sep 23 '22 21:09

Challenger5