Skip to content

Suggest self instead of &self for : Copy types #12078

Open
@nyurik

Description

@nyurik

Summary

When type implements Copy trait, especially when its size is small (e.g. an enum without variables), it would make sense to suggest changing signature to pass-by-value.

Lint Name

trivially_copy_pass_by_ref

Reproducer

I tried this code with pedantic clippy:

#[derive(Clone, Copy)]
pub enum Format {
    Gif,
    Jpeg,
    Json,
    Mvt,
    Png,
    Webp,
}

pub fn main() {
    let v = Format::Gif;
    let _ = v.use_ref();
    let _ = v.use_self();
    let _ = v.use_ref();
    let _ = v.use_self();
}

impl Format {
    // This is NOT optimal because of the reference
    #[inline(never)]
    pub fn use_ref(&self) -> bool {
           match *self {
            Self::Png | Self::Jpeg | Self::Gif | Self::Webp => true,
            Self::Mvt | Self::Json => false,
        }
    }

    // This function should not generate a warning
    #[inline(never)]
    pub fn use_self(self) -> bool {
        match self {
            Self::Png | Self::Jpeg | Self::Gif | Self::Webp => true,
            Self::Mvt | Self::Json => false,
        }
    }
}

I expected to see this happen:
A suggestion to use self instead of &self

Instead, this happened:
no warnings

Assembly

https://rust.godbolt.org/z/xxf6eqcax

example::Format::use_self:
        and     dil, -2
        cmp     dil, 2
        setne   al
        ret

example::Format::use_ref:
        movzx   eax, byte ptr [rdi]   # <-- memory access is slower than register access
        and     al, 6
        cmp     al, 2
        setne   al
        ret

Version

rustc 1.75.0 (82e1608df 2023-12-21)
binary: rustc
commit-hash: 82e1608dfa6e0b5569232559e3d385fea5a93112
commit-date: 2023-12-21
host: x86_64-unknown-linux-gnu
release: 1.75.0
LLVM version: 17.0.6

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsC-bugCategory: Clippy is not doing the correct thingI-false-negativeIssue: The lint should have been triggered on code, but wasn'tS-needs-discussionStatus: Needs further discussion before merging or work can be started

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions