Skip to content

New lint suggestion: Avoid inherent methods on generic smart pointers #11820

Open

Description

What it does

Generic smart pointers like Box<T>, Rc<T> and so on are recommended to use associated functions instead of inherent methods to avoid compatibility hazards with Deref. As an example, see Box::leak. This is also documented in the Rust API Guidelines.

This lint warns on every inherent method on types that implement Deref in a fully generic fashion.

(In particular, it should activate when type Target = T, but not when type Target = u8 or type Target = [T]).

Advantage

  • Avoid confusing overlapping methods.
  • Prevent SemVer issues with adding new inherent methods to smart pointers (which would potentially be shadowing user-defined methods).

Drawbacks

  • Using the new code is slightly more cumbersome for the user.
  • Changing the code as the lint suggests would be a breaking change for an already released crate.

Example

use std::ops::Deref;

pub struct MySmartPointer<T>(pub T);

impl<T> Deref for MySmartPointer<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> MySmartPointer<T> {
    pub fn foo(&self) {
        unimplemented!()
    }
}

Could be written as:

// ... snip

impl<T> MySmartPointer<T> {
    pub fn foo(this: &Self) {
        unimplemented!()
    }
}

Or, in the case where the user has read and understood the drawbacks, be explicitly allowed:

// ... snip

impl<T> MySmartPointer<T> {
    #[allow(clippy::bikeshed_lint_name)]
    pub fn foo(&self) {
        unimplemented!()
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions