Some questions about `enum`s

โš“ Rust    ๐Ÿ“… 2025-07-10    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 2      

surdeus

This is just self-made exercise. Let's take an enumeration:

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    // ...
}

I am exploring the quote below, without that much concern about the original context:

Rust sees that Message::Quit doesnโ€™t need any space, (...)

First aspect: Does it have a value?

No value at all seems impossible. When we test in a match:

match instance {
    Message::Quit => //...
    /*...other variants ... */
}

it's comparing two values. So it is represented by a value, but as the text says, it may still not store a value, I suppose.

Second aspect: a simple model

Maybe an initial, simplified model of an enum instance could be

  1. Identity: A value for the enumeration variant, as shown below (a numeric Identifier)

    enum Enum {
    Baz,  // or Baz = 0
    Bar,   // or Bar = 1
    // etc
    }
    
  2. Data: for field-full Variants the data or a pointer to the data. Field-less have nothing.

Number 1. is also what I interpret from the enums::reference.

In this case, the reason why ::Quit would not take space is that it has no data, but not that there isn't any information about itself / its variant in memory (which seems ridiculous but who knows.) It's value would be, say, 0.

Third aspect: Variants with Data

How does it extend to field-full variants like Move(i32,i32)?

When we do a match would it be comparing:

  1. Something like a 2 assigned
  2. And then each number
match instance {
    // each is a "2"-id-match, 
    // then tests "data" fields
    Message::Move(1,2)=>// ...
    Message::Move(4,5)=>//...
    /*...other variants ... */
}

I'm just hoping for corrections, links or interesting considerations you would add.

6 posts - 5 participants

Read full topic

๐Ÿท๏ธ rust_feed