rust-lang / rust-lang/reference

Reference recommends union pattern matching pattern that is not actually guaranteed to work

Open
#2,298 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Rust
Stars
1.6k
Forks
607
PR merge metrics
PR metrics pending

Description

The reference recommends code like this

#[repr(u32)]
enum Tag { I, F }

#[repr(C)]
union U {
    i: i32,
    f: f32,
}

#[repr(C)]
struct Value {
    tag: Tag,
    u: U,
}

fn is_zero(v: Value) -> bool {
    unsafe {
        match v {
            Value { tag: Tag::I, u: U { i: 0 } } => true,
            Value { tag: Tag::F, u: U { f: num } } if num == 0.0 => true,
            _ => false,
        }
    }
}

However, we don't actually guarantee the order in which patterns are evaluated, and in fact some variants of this pattern are UB today.

It's unclear how this example ended up there, it exists at least since https://github.com/rust-lang/reference/commit/ae361e1a09437dd75a15416a6a369226c5ca5ab7 which is 8 years old (Github is too broken right now to easily track this back further). None of the folks involved in opsem or pattern matching (or at least, neither @Nadrieril nor me) were aware of this.

It's probably too late to take this pattern out of the reference, it will already have been copied many times...

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Rust Reference union pattern subpattern section linked in the issue, then read the related UB report in rust-lang/rust#158387. Determine how the example should be qualified or revised so it does not imply an evaluation order guarantee. Done means the Reference no longer recommends a pattern that can be undefined behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.