Skip to content

Wrong lint in case of to_*_mut method #6758

@dodomorandi

Description

@dodomorandi

Lint name: wrong_self_convention

I tried this code:

pub enum Test<T> {
    None,
    One(T),
    Many(Vec<T>),
}

impl<T> Test<T> {
    pub fn to_many(&self) -> Option<&[T]> {
        match self {
            Self::Many(data) => Some(data),
            _ => None,
        }
    }

    pub fn to_many_mut(&mut self) -> Option<&mut [T]> {
        match self {
            Self::Many(data) => Some(data),
            _ => None,
        }
    }
}

I expected to see this happen: in order to get an optional variant of the enum, the naming convention to_* should be used, because the match statement cannot be considered free (therefore as_* is not ok). Moreover, the name to_mut (à la Cow::to_mut) cannot be used in this case, because there are two non-empty variants. Therefore using to_many_mut for the name of the method seems the right choice.

Instead, this happened: clippy says that to_* should follow the convention of taking self by reference.

My rationale is that, when a method starts with to_, it should expect a &mut self parameter if ends with _mut, otherwise &self.

Meta

  • cargo clippy -V: clippy 0.0.212 (cb75ad5 2021-02-10)
  • rustc -Vv:
    rustc 1.50.0 (cb75ad5db 2021-02-10)
    binary: rustc
    commit-hash: cb75ad5db02783e8b0222fee363c5f63f7e2cf5b
    commit-date: 2021-02-10
    host: x86_64-unknown-linux-gnu
    release: 1.50.0
    

Metadata

Metadata

Assignees

Labels

C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't havegood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions