Why can't I `use Self::*` in an enum's impl?

I've already read this post, but that seems to talk about an issue that has been resolved (rust-lang/rust#56225).

Assuming this enum:

pub enum MyType {
    Foo,
    Bar,
    Baz,
}

I can use either of these options to refer to the variants of MyType:

impl MyType {
    pub fn new_foo() -> Self {
        Self::Foo
    }

    pub fn new_bar() -> Self {
        use MyType::*;
        Bar
    }
}

However, attempting to combine the two methods fails:

impl MyType {
    pub fn new_baz() -> Self {
        use Self::*;
        Baz
    }
}

Why is this?

playground link for the above snippets

Even though this doesn’t answer the question, note that the behavior is the same for type aliases or use statements without the * like use Self::Baz.

pub enum MyType {
    Foo,
    Bar,
}

type Alias = MyType;

impl MyType {
    pub fn new_foo() -> Self {
        Alias::Foo // works
    }

    pub fn new_bar() -> Self {
        use Alias::Bar; // doesn’t work; Alias::* wouldn’t work either
        Bar
    }
}

(playground)

Edit: Here’s an issue asking the same question

as far as I understand, I would guess (without knowing the compiler internals myself) that the reason why use Self::* doesn’t work is something along the lines of

  • Self is like an implicitly defined type alias
  • type aliases are part of the type system and are only resolved by the type-checker
  • use statements relies on the module system and not the type system
  • resolving paths like MyType::* (or more precisely: resolving something like Foo in the presence of such a use statement) has to happen much earlier in compilation than type checking
10 Likes

Thanks @steffhan, I was having trouble searching for the phrase "use Self::*" with so many symbols!

It looks like it was a conscious design by the lang team to not allow this to work; I guess I'll just settle for one of the other options.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.