by styfle · 6y ago · 0 comments
Why does Rust destructuring require the struct name? The example uses:
let Person { name, city } = person;
This seems a little verbose since I would expect the type system to know that person is of type Person already.Is this because destructuring syntax is trying to be compatible with the pattern matching syntax?
It isn't in the language yet due to a combination of subtle issues that need to be considered before a final design can be reached, trying to keep the grammar clean, accepting that explicitness and verboseness now is better than hastily moving towards something that seems better but that can introduce technical, documentation or understandability issues.
> Is this because destructuring syntax is trying to be compatible with the pattern matching syntax?
It's not trying to be compatible, it is pattern matching syntax. If the language changed to, for example, allow the following
let _ { name, city } = person;
Would also allow match opt_person {
Some(_ { name, city }) => {}
None => {}
}
[1]: https://internals.rust-lang.org/t/pre-rfc-struct-constructor...[2]: https://internals.rust-lang.org/t/pre-rfc-implied-type-for-p...
[3]: https://internals.rust-lang.org/t/pre-rfc-anonymous-struct-a...
fn takes_person(p: Person) {
fn takes_person(Person {name, city}: Person) {
But I wouldn't inherently say that's the reason, it's also because structs are nominally rather than structurally typed.