rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.5k stars 1.55k forks source link

Elide lifetime in trait #10394

Open amab8901 opened 1 year ago

amab8901 commented 1 year ago

Summary

Lifetime could be elided in the trait, but Clippy didn't notice that. Please add correction to clippy so that it warns about it and suggests to elide it

Lint Name

needless_lifetimes

Reproducer

I tried this code (copy+paste into main() function):

    #[derive(Debug)]
    pub enum Key<'a> {
        Ref(&'a [u8]),
        Val8([u8; 1]),
        Val16([u8; 2]),
        Val32([u8; 4]),
        Val64([u8; 8]),
        Val128([u8; 16]),
    }

    impl<'a> AsRef<[u8]> for Key<'a> {
    fn as_ref(&self) -> &[u8] {
        match self {
            Key::Ref(r) => r,
            Key::Val8(v) => v,
            Key::Val16(v) => v,
            Key::Val32(v) => v,
            Key::Val64(v) => v,
            Key::Val128(v) => v,
        }
    }
}

    pub trait Prefixer<'a> {
        /// returns 0 or more namespaces that should be length-prefixed and concatenated for range searches
        fn prefix(&self) -> Vec<Key>;

        // fn joined_prefix(&self) -> Vec<u8> {
        //     let prefixes = self.prefix();
        //     namespaces_with_key(&prefixes.iter().map(Key::as_ref).collect::<Vec<_>>(), &[])
        // }
    }
    impl<'a> Prefixer<'a> for Vec<u8> {
        fn prefix(&self) -> Vec<Key> {
            vec![Key::Ref(self.as_ref())]
        }
    }

I expected to see this happen: Clippy should warn about this paragraph:

impl<'a> Prefixer<'a> for Vec<u8> {
    fn prefix(&self) -> Vec<Key> {
        vec![Key::Ref(self.as_ref())]
    }
}

Clippy should suggest to replace it with the following:

impl Prefixer<'_> for Vec<u8> {
    fn prefix(&self) -> Vec<Key> {
        vec![Key::Ref(self.as_ref())]
    }
}

Note that the changes are in the first line of the quoted paragraph, and particularly the lifetime parameters being simplified from two instances of <'a> into just one instance of <'_>

Instead, this happened: clippy had nothing to say about this code

Version

rustc -Vv
rustc 1.68.0-nightly (0442fbabe 2023-01-10)
binary: rustc
commit-hash: 0442fbabe24ec43636a80ad1f40a0ad92a2e38df
commit-date: 2023-01-10
host: x86_64-unknown-linux-gnu
release: 1.68.0-nightly
LLVM version: 15.0.6
HKalbasi commented 1 year ago

It also doesn't warn for inherent impls:

struct S<'a>(&'a i32);
impl<'a> S<'a> {}