rust-lang / rust-lang/rust

Lint on `as_deref` from `&&T` to `&&T` or `&T` to `&T`, to catch people thinking "deref" dereferences

Open
#131,272 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics A-lints
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I recently watched a Rust coding livestream, and someone had an Option<&&'static str> (obtained from HashMap::keys() on a HashMap with &'static str keys). They wanted to get an Option<&'static str>.

They initially tried reaching for as_deref(), because it had deref in it so they assumed it dereferenced. This seems like a likely trap for new developers.

I think we should flag cases where someone calls as_deref on a type that's statically known to contain a reference (e.g. Option<&T> or Option<&&T>, or likewise for Result) and gets back exactly the same type, particularly if there's a type error saying that they needed the dereferenced type. The lint could tell them they might want .copied() or .cloned() (depending on whether the type implements Copy or Clone).

Simple example:

fn main() {
    let mut m: HashMap<&'static str, &'static str> = HashMap::new();
    m.insert("hello", "world");
    let k = m.keys().next();
    let dereferenced: Option<&'static str> = k.as_deref();
    println!("{dereferenced:?}");
}

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 by locating Rust's lint implementation and existing lint tests for Option and Result methods. Use the examples in the issue to check reference-containing types, and consider the proposed copied or cloned guidance as part of the completed diagnostic.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.