rust-lang / rust-lang/rust-clippy
New lint: deref coercions
@yegeunyang is already working on this.
Since Jan 21, 2025.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
Lints on any use of deref coercions - for example, accessing a field or method through a Deref impl
Categories (optional)
- Kind: Restriction lint
What is the advantage of the recommended code over the original code
Normally, deref coercions are a very useful part of rust, making smart points like Box, Rc, Ref, and RefMut much easier to use. However, this can be undesirable when writing unsafe code, since a non-trivial function call could be completely hidden from view. For example:
- Unsafe code can temporarily put data structures in an unusual state, which will lead to undefined behavior if dropped (e.g.
Vec::set_len). A deref coercion might cause a panic at an unexpected point (due to a panicking user-suppliedDerefimpl), leading to undefined behavior. - When mixing raw pointers and references, it's important to pay attention to the provenance of pointers. A deref coercion can hide the creation of an
&selfreference behind what looks like a normal field access, leading to a very subtle form of undefined behavior.
Drawbacks
This would be a fairly niche lint - unless you're writing unsafe code, there's little need to use it.
Example
fn main() {
let a = Box::new(true);
let b: &bool = &a;
}
Could be written as:
use std::ops::Deref;
fn main() {
let a = Box::new(true);
let b: &bool = (&a).deref();
}
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.