Suggestion: infer type on LHS of destructure

When destructuring a struct, it’s pretty annoying to have to write out the name of the struct. It usually leads to redundancy as the type of the struct is knowable from context. An example:

struct Point<T> {
    x: T,
    y: T,
}

// `Point` is repeated in the function argument destructure
fn pt_to_tup_1<T>(Point { x, y }: Point<T>) -> (T, T) {
    (x, y)
}

fn pt_to_tup_2<T>(point: Point<T>) -> (T, T) {
    // `Point` is repeated in the destructure
    let Point { x, y } = point;
    (x, y)
}

In both cases Point is unnecessarily (except that the compiler requires it) specified on the LHS even though it's inferable from the RHS; the only thing something of type Point<T> can be destructured into is another Point (right?). Having to name the type in order to destructure it gets particularly annoying when the type has a long name or needs qualification due to not yet being in scope.

I'd like to be able to write the following but this is currently not allowed.

fn pt_to_tup_3<T>(_ { x, y }: Point<T>) -> (T, T) {
    (x, y)
}

fn pt_to_tup_4<T>(point: Point<T>) -> (T, T) {
    let _ { x, y } = point;
    (x, y)
}
  1. Are there any plans to add this to the language?
  2. If not, what's the way to go about proposing this?
  3. Is this the right forum to ask such questions and make language related suggestions?

Is this the right forum to ask such questions and make language related suggestions?

The forum for that is IRLO:

what's the way to go about proposing this?

You would create an RFC and send a PR for it. However, before doing this, search previous RFC PRs and IRLO for similar proposals. It is very likely that this idea has come up before ("what if we could omit this name?" is a frequent thought), so if you want your proposal to be accepted, you need to review the previous reasons similar ideas might not have been accepted, figure out what would address those issues, and design a better solution than previous ones.

3 Likes

This has been discussed many times, for both structs and enum variants. Here's one such thread:

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.