rust-lang / rust-lang/rust-clippy

`mut_mutex_lock` in closures doesn't consider `Fn` bound

Open
#13,720 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug I-false-positive
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

Summary

When a &mut Mutex<T> is given and used in a closure, the lint fails to consider the type constraints on the given closure, and wrongfully suggests get_mut which would require a FnMut bound instead of Fn, creating code that fails to compile.

Lint Name

mut_mutex_lock

Reproducer

I tried this code:

use std::sync::Mutex;

fn _closure(_: impl Fn()) {}
fn _func(mutex: &mut Mutex<()>) {
    _closure(|| {
        let _guard = mutex.lock();
    })
}

I saw this happen:

warning: calling `&mut Mutex::lock` unnecessarily locks an exclusive (mutable) reference
 --> src/lib.rs:6:28
  |
6 |         let _guard = mutex.lock();
  |                            ^^^^ help: change this to: `get_mut`
  |
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#mut_mutex_lock
  = note: `#[warn(clippy::mut_mutex_lock)]` on by default

I expected to see this happen:
No lint

Version
rustc 1.81.0 (eeb90cda1 2024-09-04)
binary: rustc
commit-hash: eeb90cda1969383f56a2637cbd3037bdf598841c
commit-date: 2024-09-04
host: x86_64-unknown-linux-gnu
release: 1.81.0
LLVM version: 18.1.7
Additional Labels

No response

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 by locating the implementation and tests for the mut_mutex_lock lint, then run the Rust reproducer from the issue. Check how closure trait bounds are considered before suggesting get_mut. Done means an Fn closure using &mut Mutex is not linted when the suggestion would fail to compile.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.