Skip to content

explicit_auto_deref overeager with Any #9143

Closed
@ezrosent

Description

@ezrosent

Summary

My read is that this is a separate bug to those fixed in #9126, apologies if it is actually the same.

Lint Name

explicit_auto_deref

Reproducer

I tried this code, which completes successfully:

use std::any::Any;
struct C(Box<dyn Any>);
impl C {
    fn new<T: Any>(t: T) -> C {
        C(Box::new(t))
    }
    fn as_any(&self) -> &dyn Any {
        &*self.0
    }
}
fn main() {
    assert_eq!(C::new(0usize).as_any().downcast_ref::<usize>().unwrap(), &0);
}

Clippy gives the following output

warning: deref which would be done by auto-deref
 --> src/main.rs:9:10
  |
9 |         &*self.0
  |          ^^^^^^^ help: try this: `self.0`
  |
  = note: `#[warn(clippy::explicit_auto_deref)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#explicit_auto_deref

But replacing as_any with the suggestion:

fn as_any(&self) -> &dyn Any {
    &self.0
}

Causes the program to fail (downcast_ref now returns None). This is (presumably) because self.0 has type Box<dyn Any>, which itself implements Any, so the suggested rewrite does not behave the same as the original code.

Version

rustc 1.64.0-nightly (1517f5de0 2022-07-07)
binary: rustc
commit-hash: 1517f5de01c445b5124b30f02257b02b4c5ef3b2
commit-date: 2022-07-07
host: aarch64-apple-darwin
release: 1.64.0-nightly
LLVM version: 14.0.6

Additional Labels

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't have

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions