Skip to content

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

Description

@RalfJung

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 ae361e1 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...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions