0

While I was reading The Rust Programming Language, I came across the statement (emphasis mine):

To determine how much space to allocate for a Message value, Rust goes through each of the variants to see which variant needs the most space. Rust sees that Message::Quit doesn’t need any space, Message::Move needs enough space to store two i32 values, and so forth. Because only one variant will be used, the most space a Message value will need is the space it would take to store the largest of its variants.

The Message enum is defined as:

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

What does the bold statement mean in detail?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
109149
  • 1,223
  • 1
  • 8
  • 24
  • 1
    It does the same thing as any other language supporting discriminated unions, that is: calculate the memory requirement for each alternative, pick the largest value, add fixed overhead for discriminant. – oakad Oct 21 '20 at 10:17
  • Fixed overhead for discriminant? What does this mean? – 109149 Oct 21 '20 at 10:23
  • 2
    Let's say you construct your message using a string. How does the receiver of your message knows it's a string and not a number tuple (that is, option 3 rather than any other option)? – oakad Oct 21 '20 at 10:30
  • 1
    I understand now, it's like a metadata. You can write down answer. – 109149 Oct 21 '20 at 10:48

0 Answers0