New lint suggestion: Avoid inherent methods on generic smart pointers · Issue #11820 · rust-lang/rust-clippy (original) (raw)

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

Drawbacks

Example

use std::ops::Deref;

pub struct MySmartPointer(pub T);

impl Deref for MySmartPointer { type Target = T;

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

}

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

Could be written as:

// ... snip

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

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

// ... snip

impl MySmartPointer { #[allow(clippy::bikeshed_lint_name)] pub fn foo(&self) { unimplemented!() } }