Skip to content

If-Let-Else and Let-Else doesn't produce same result which creates UB. #134766

Closed as not planned
@Azvanzed

Description

@Azvanzed

I tried this code:

static MUTEX: spin::Mutex<Option<fn()>> = spin::Mutex::new(None);

// SAMPLE A
fn main() {
    let Some(value) = *MUTEX.lock() else {
         unreachable!("Mutex not set");
     };

     value();
 }

// SAMPLE B
fn main() {
    if let Some(value) = *MUTEX.lock() {
        value();
    } else {
        unreachable!("Mutex not set");
    }
 }

I expected to see this happen:
A. calls the value function then the mutex unlocks. (IDA decompilation)

Image

Instead, this happened:
B. mutex unlocks then calls the value function. (IDA decompilation)

Image

Meta

The bug does occur in nightly.

rustc --version --verbose:

rustc 1.83.0 (90b35a623 2024-11-26)
binary: rustc
commit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf
commit-date: 2024-11-26
host: x86_64-pc-windows-msvc
release: 1.83.0
LLVM version: 19.1.1
Backtrace

Not needed since this is visible statically.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions