Initialization syntax for Self tuple structs

I’ve suggested a new enhancement request: https://github.com/rust-lang/rust/issues/42601

An example usage:

struct VecA { x: u32, y: u32 }
impl VecA {
    fn new() -> Self {
        Self { x: 0, y: 0 } // OK
    }
}
struct VecB(u32, u32);
impl VecB {
    fn new() -> Self {
        Self(0, 0) // Error
    }
}
fn main() {}

The current error message is:

error[E0423]: expected function, found self type `Self`
  --> ...\test.rs:10:9
   |
10 |         Self(0, 0) // Error
   |         ^^^^ did you mean `Self { /* fields */ }`?

The use of “Self(0, 0)” looks symmetrical with the “Self { x: 0, y: 0 }” syntax, and it allows to write code a little more DRY.

2 Likes

Hmm, there’s actually a real VecB function in the same namespace as struct VecB, which couldn’t work with Self. But maybe that wouldn’t stop it from have an aliased Self “function” within the type methods.

This is totally doable, it just introduces some novel concept into the language - “value alias” (like type aliases type A = u8;, but for values).
It would be a bit a bit strange to support such a thing, but make it available only for Self.

(There are also a couple of questions to solve - what exactly generic parameter substitutions are used for this Self, how hard we work to retrieve this Self (e.g. is it available if the impl is for a type alias (maybe even associated) of a struct with a constructor, but not for the struct itself).)

This would be helpful in generated code, as it removes the need to know a type’s ident when generating impls.

3 Likes

I just ran into exactly this.

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