1

I'm trying to understand the Rust Enum type. Specifically the Union Enum.

Let's start with the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d46d65fc688c1cff48a50077c6d7ddf2

fn main() {
    enum ABC {
        A(u64),
        B,
        C,
    };

    let ins = ABC::A(5);

    match ins {
        ABC::A(_) => println!("A"),
        ABC::B => println!("B"),
        ABC::C => println!("C"),
    };
}

This code runs fine. Now let's try to define the type ins as ABC::A but without specifying the union. Logically, it should not work; and it does not.

fn main() {
    enum ABC {
        A(u64),
        B,
        C,
    };

    let ins = ABC::A;

    match ins {
        ABC::A(_) => println!("A"),
        ABC::B => println!("B"),
        ABC::C => println!("C"),
    };
}

However, the error message is a little bit confusing:

error[E0308]: mismatched types
  --> src/main.rs:11:9
   |
11 |         ABC::A(_) => println!("A"),
   |         ^^^^^^^^^ expected fn item, found enum `main::ABC`
   |
   = note: expected type `fn(u64) -> main::ABC {main::ABC::A}`
              found type `main::ABC`

It does seem that Rust is not complaining about declaring an enum variable without its union but about something else which I don't understand.

Let's try this code:

fn main() {
    enum ABC {
        A(u64),
        B,
        C,
    };

    let ins = ABC::A;
}

This code compiles. Interesting because I didn't expect it to. Logically, Rust should complain that we didn't specify a u64?

Let's try to find out the type of this enum union:

fn main() {
    enum ABC {
        A(u64),
        B,
        C,
    };

    let ins = ABC::A;

    let integer: u32 = ins;
}

We get the following error which should reveal the type of ins

error[E0308]: mismatched types
  --> src/main.rs:10:24
   |
10 |     let integer: u32 = ins;
   |                        ^^^ expected u32, found fn item
   |
   = note: expected type `u32`
              found type `fn(u64) -> main::ABC {main::ABC::A}`

So is ins some kind of a function? Or am I missing something else?

Omar Abid
  • 15,753
  • 28
  • 77
  • 108
  • Because `ABC::A` is a function that constructs the variant `A` of the enum. Example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=163ecf26974858df09439cbb1c2e54fa – Boiethios Jul 11 '19 at 15:29
  • Thanks. I had difficulty find the right words. I'll read the question and get back here. – Omar Abid Jul 11 '19 at 15:46

0 Answers0