Rfcs: Rustc should throw a helpful warning on useless "self" argument in methods.

Created on 23 Dec 2016  ·  5Comments  ·  Source: rust-lang/rfcs

When we have a code which does not need the self object we may simply say that it can be removed.

struct A(u64);
impl A {
    fn m1(&self) { // warning: unused self can be removed
        println!("Hello world");
    }

    fn m2(&mut self) { // warning: unused self can be removed
        println!("Hello again");
    }
}

Though, this warning should have a possibility to be ommited. And, for example, there are some special cases, one of which @eddyb has pointed me to: if we have a trait which requires method to accept self as a parameter, we don't need to emit such warning:

struct A(u64);
trait Printable {
    fn m1(&self);
}
impl Printable for A {
    fn m1(&self) { // no warning is here
        println!("Printed!");
    }
}

The reason of that is making easier to refactor this code in the future (especially if it is very long and we must read the whole method body just to understand that it does not depend on object at all) and to allow code users to call this method without an object.

If this idea gets approved, I would like to implement it by myself. But I have no idea how to work with it so I would like to get some advices where to look at, in learning purposes. I love rust and I want to help to make it better as much as I can.

T-compiler

Most helpful comment

There's actually a special case to silence such warnings on self - if we change that, we have to at least keep them silenced in trait impls, where the trait dictates whether there's any self.

All 5 comments

There's actually a special case to silence such warnings on self - if we change that, we have to at least keep them silenced in trait impls, where the trait dictates whether there's any self.

Also, sometimes you want to take a parameter, but not use it yet; for most things, you can use _ or _ident, but it's impossible to do the same with self.

Would _self, &_self, and &mut _self work?

@burdges since self is a keyword I doubt it would, _self would likely just be a first parameter named self.

Also, since having self makes it possible to call the function in method position, removing a self parameter makes a dramatic syntactic difference. This seems like it should probably be a default-off warning, which means maybe someone could take a stab at putting it in clippy first in order to see how useful it is.

I suppose let _ = self; is the right solution then, no?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

3442853561 picture 3442853561  ·  3Comments

burdges picture burdges  ·  3Comments

steveklabnik picture steveklabnik  ·  4Comments

rudolfschmidt picture rudolfschmidt  ·  3Comments

mqudsi picture mqudsi  ·  3Comments