rust-lang/rust-clippy

New lint: deref coercions

Open

#7,104 opened on Apr 17, 2021

View on GitHub
 (6 comments) (0 reactions) (1 assignee)Rust (10,406 stars) (1,391 forks)batch import
A-lintL-restrictiongood first issue

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-supplied Deref impl), 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 &self reference 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