Question Details

No question body available.

Tags

rust enums bit-fields

Answers (2)

Accepted Answer Available
Accepted Answer
September 8, 2025 Score: 2 Rep: 76,955 Quality: Medium Completeness: 40%

Because you can take a reference to the bool, and give it to code that knows nothing about the original type. Therefore the value of the whole byte of bool must be 1 or 0, it cannot be anything else.

September 8, 2025 Score: 6 Rep: 27,271 Quality: High Completeness: 80%

Because the payload of an enum variant has to be individually addressable, at addressing unit (i.e. byte) granularity.

Take this example:

fn change(b: &mut bool); // opaque

fn getchanged(mut r: Result) -> Result { match r { Ok(ref mut b) => change(b), Err(ref mut b) => change(b), }; r }

change must be able to manipulate the borrowed bool without knowing it is actually embedded within a Result and has to have some of its bits preserved. For example, change may perform a bytewise memory copy into the place borrowed by b.

For a more drastic example:

fn swappayloads(r: &mut Result, s: &mut Result) {
  let a: &mut bool = match r { Ok(x) => x, Err(x) => x, };
  let b: &mut bool = match s { Ok(x) => x, Err(x) => x, };
  std::mem::swap(a, b);
}

std::mem::swap performs a bytewise swap. If Result were packed into a single byte, std::mem::swap would have swapped not just payloads, but discriminants as well.

For this reason, the payload of a Result must be stored at a distinct address from the discriminant.

There have been discussions about adding a feature that can prohibit referencing sub-fields within a data type, so that this optimization can happen (e.g. https://internals.rust-lang.org/t/towards-even-smaller-structs/14686/), but it seems none have come to fruition as of 2025.