rust-lang / rust-lang/rust-clippy
clippy::replace_box suggests a MachineApplicable fix that is semantically questionable for Box<&mut T>
@DoTuanAnh2k1 is already working on this.
Since Aug 12, 2026.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
Summary
Hi, thanks for the great tool!
Clippy’s replace_box lint flags Box::new(...) assignments to an existing Box and suggests writing to the inner value instead. The suggestion is marked MachineApplicable, but in the case where the boxed type is itself a mutable reference (Box<&mut T>), the suggested fix is semantically different from the original code and can be misleading regarding borrow/lifetime behavior.
Reproducer
fn main() {
let mut raphael = 300;
let mut samuel = Box::new(&mut raphael);
**samuel += 500;
let mut albert = 900;
samuel = Box::new(&mut albert);
}
Clippy output
warning: creating a new box
--> src/main.rs:9:5
|
9 | samuel = Box::new(&mut albert);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace existing content with inner value instead: `*samuel = &mut albert`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#replace_box
Issue
The two forms are not equivalent here:
// original (linted)
samuel = Box::new(&mut albert);
// suggested fix
*samuel = &mut albert;
Both assign a mutable reference into the Box, but the lint fires only on the Box::new(...) spelling and suggests rewriting it to the deref-assignment form. For Box<&mut T> this ignores the reference’s lifetime implications; the deref-assign form can behave differently (or even be rejected by the borrow checker) depending on the lifetimes involved. Since the suggestion is marked MachineApplicable, a user applying it may silently change semantics or end up with a borrow-check error for code that previously compiled.
Expected behavior
The suggestion should either:
be restricted to cases where the inner type is not itself a reference (or is otherwise lifetime-free), or
not be emitted as MachineApplicable for Box<&mut T>.
Version
Additional Labels
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.