rust-lang / rust-lang/rust-clippy

Warn on &mut to a temporary value

Open
#8,712 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

Warn when &mut is taken on a temporary value, especially when type implements Copy. Code below doesn't modify buf, because what is being passed to t is a &mut to a temporary array created by a <[u8]>::try_into():

&mut reference implies that a receiver will modify value, modifying temporary value, which user has no access to is pointless IMHO. More likely than not, it is not user intention.

Lint Name

mut-ref-rvalue

Category

suspicious

Advantage

No response

Drawbacks

No response

Example
#[inline(never)]
pub fn t(b: &mut [u8;4]) {
    b[0] = 99;
}

#[inline(never)]
pub fn tt() -> [u8;16] {
    let buf = [0u8; 16];
    t(&mut buf[..4].try_into().unwrap());
    buf
}

Could be written as:

#[inline(never)]
pub fn t(b: &mut [u8;4]) {
    b[0] = 99;
}

#[inline(never)]
pub fn tt() -> [u8;16] {
    let mut buf = [0u8; 16];
    t((&mut buf[..4]).try_into().unwrap());
    buf
}

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

The issue names no implementation files or tests. Start with the proposed examples and inspect existing Clippy suspicious lints to define the temporary-value and Copy cases; done means a mut-ref-rvalue lint warns on the shown temporary reference while accepting the mutable-local rewrite.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.