Skip to content

Scrutinee dropped after if-let body #133677

Closed
@Aquam4n

Description

@Aquam4n

Objects inside block expressions in the scrutinee of an if-let statement are not dropped before the body.

This is inconsistent both with declaring a temporary variable, e.g. x in test #2, and let-else behavior in test #3.

I tried this code:

fn main() {
	struct S(i32);
	impl Drop for S {
		fn drop(&mut self) {
			println!("Dropped S {}", self.0)
		}
	}

	println!("--- test 1");
	{
		println!("Before if-let");
		if let _ = { S(1).0 } {
			println!("Inside body");
		}
	}

	println!("--- test 2");
	{
		println!("Before if-let");
		let x = { S(2).0 };
		if let _ = x {
			println!("Inside body");
		}
	}

	println!("--- test 3");
	{
		println!("Before let-else");
		let _ = ({ S(3).0 }) else { unreachable!() };
		println!("After let-else");
	}
}

I expected to see this happen:

--- test 1
Before if-let
Dropped S 1
Inside body
--- test 2
Before if-let
Dropped S 2
Inside body
--- test 3
Before let-else
Dropped S 3
After let-else

Instead, this happened:

--- test 1
Before if-let
Inside body
Dropped S 1
--- test 2
Before if-let
Dropped S 2
Inside body
--- test 3
Before let-else
Dropped S 3
After let-else

Meta

Same behavior on both stable and nightly.

rustc --version --verbose:

rustc 1.82.0 (f6e511eec 2024-10-15)
binary: rustc
commit-hash: f6e511eec7342f59a25f7c0534f1dbea00d01b14
commit-date: 2024-10-15
host: x86_64-unknown-linux-gnu
release: 1.82.0
LLVM version: 19.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsC-discussionCategory: Discussion or questions that doesn't represent real issues.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions