Skip to content

significant_drop_in_scrutinee is confusing and not very useful for for loops #8987

Closed
@crumblingstatue

Description

@crumblingstatue

Description

The following code

use std::sync::Mutex;

fn main() {
    let mutex_vec = Mutex::new(vec![1, 2, 3]);
    for number in mutex_vec.lock().unwrap().iter() {
        dbg!(number);
    }
}

produces this clippy output:

warning: temporary with significant drop in for loop
 --> src/main.rs:5:19
  |
5 |     for number in mutex_vec.lock().unwrap().iter() {
  |                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(clippy::significant_drop_in_scrutinee)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#significant_drop_in_scrutinee

The first confusing thing is the name. Scrutinee only makes sense for match, it's not used in the context of for loops.
If one visits the lint page, it doesn't talk about for loops at all, and what the ideal code would look like for for loops.

The naive thing to do here would be to bind the guard before the for loop (ignoring that it still triggers the lint (#8963)).

use std::sync::Mutex;

fn main() {
    let mutex_vec = Mutex::new(vec![1, 2, 3]);
    let guard = mutex_vec.lock().unwrap();
    for number in guard.iter() {
        dbg!(number);
    }
}

However, that actually increases the scope of the guard, and now it will be locked for the entire lifetime of the guard binding.
The proper thing to do would be to drop it after the for loop.

use std::sync::Mutex;

fn main() {
    let mutex_vec = Mutex::new(vec![1, 2, 3]);
    let guard = mutex_vec.lock().unwrap();
    for number in guard.iter() {
        dbg!(number);
    }
    drop(guard);
}

However, the lint page never talks about this, and this could easily be a trap for beginners/people not paying attention.
And is it really better than just locking in the for loop expression?
I personally think it's pretty clear that the guard lasts for the whole loop.
Abiding this lint just adds a new opportunity for error (dropping the guard late).

Version

rustc 1.63.0-nightly (ec55c6130 2022-06-10)
binary: rustc
commit-hash: ec55c61305eaf385fc1b93ac9a78284b4d887fe5
commit-date: 2022-06-10
host: x86_64-unknown-linux-gnu
release: 1.63.0-nightly
LLVM version: 14.0.5

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    I-false-positiveIssue: The lint was triggered on code it shouldn't havegood first issueThese issues are a good way to get started with Clippy

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions