Allow destructuring self with @ bindings

First of all, I am aware of the Github issue Implement UFCS (Tracking RFC 132) and why the name self cannot be made insignificant. A function is a method if and only if its first argument is called self - I agree with this and I do not propose to change this.

However, why won't this work?

struct S {
    i: i32,
    f: f64,
}

impl S {
    fn fun(self @ Self {i, f} : Self) {
        println!("{i}, {f}");
    }
}

fn main() {
    let s = S {i: 5, f: 5.5};
    s.fun();
}

I believe the above code should compile and work as expected. Yet it does not even compile.

  • The first argument of fun is called self, therefore fun should be a valid method.
  • This is valid destructuring syntax. Replace self with any other name and fun will compile & work, though it will not be a method.
4 Likes

It might be mostly that nobody has (yet) implemented it, because the ability to have bindings on both sides of @ is a fairly recent addition to the language (well, stabilized two years ago, but still…)

One gotcha is that &self and &mut self don't mean the same thing as they usually do in patterns, so allowing &mut self @ Self {…} might be somewhat confusing. But if only the longer form self @ Self {…}: &mut Self were allowed, at least at first, that wouldn't be a problem, though the repetition of "self" is slightly awkward.

(An idea: given that self is already special syntax sauce, it might also be reasonable to have a shortcut for writing a destructuring pattern, for example fn method(self { a, b, .. }))

5 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.