Rust has problems with enum variants when using Self


#1
pub enum SomeEnum {
    A(f64),
    B(f64),
    C(f64),
}

impl SomeEnum {
    pub fn new()
    -> Self
    {
        Self::A(5.0) // does not compile
    }
    
    pub fn but_this_is_ok()
    -> Self
    {
        SomeEnum::A(5.0)
    }
}

This code does not compile: https://is.gd/iC0vAp

error[E0599]: no associated item named `A` found for type `SomeEnum` in the current scope
  --> <anon>:11:9
   |
11 |         Self::A(5.0)
   |         ^^^^^^^

I know that rust had problems with using Self in constructor-like functions - is this an open issue right now? All I want to do is to avoid using my enums name. Rust obviously detects that I want to use SomeEnum, but for some reason, it doesn’t find the enum variant.


#2

Yes, this is a general problem. You can’t use Self in many cases. I think it’s worth an enhancement request…


#3

In the meantime, perhaps the following would appeal to you:

pub fn new() -> Self {
   use SomeEnum::*;
   A(5.0);
}

This obviously doesn’t help in the simple case above, but if your new function referred to more of the variants, then it would cut down the # of places you refer to the enum name.


#4

Alright, so it is an issue. Where would the best place to report this, is there a tracking issue?


#5

Allowing code as you write would lead to confusion. The Self:: identifies to the reader/compiler that the next identifier is an associated type. There is nothing to stop an identifier being of the same name as a structures members name.


#6

It can be an associated fn as well, which I find pretty close to the enum case:

struct Foo;

impl Foo {
    fn baz(_: i32) {}
    fn bar() {
        Self::baz(23);
    }
}

#7

This is part of issue 26264 and its duplicate 31168. The language team has agreed that this should be fixed, but it hasn’t happened yet because of some open design and implementation issues.


#8

@jonh yes there is: Self as a enum name would raise a "expected identifier, found keyword Self" error: http://play.integer32.com/?gist=fd305f733e87ba42a8b54da945f2ff42&version=nightly


#9

I’ve added a possibly related case to Issue #26264.