3 ms·
Question for the author: Why does Rust destructuring require the struct name? The example uses: let Person { name, city } = person; This seems a little ver
by styfle 6y ago
Question for the author:
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?
- steveklabnik 6y agoNot the author, but yes, this is because the thing between "let" and "=" is a pattern, the exact same thing used in match, and in other places. For example, function arguments! 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.
- estebank 6y agoYou will find pre-RFCs[1][2] in https://internals.rust-lang.org/ https://internals.rust-lang.org/ about this, as well as for anonymous structs[3]. 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-name-inference/10960 https://internals.rust-lang.org/t/pre-rfc-struct-constructor... [2]: https://internals.rust-lang.org/t/pre-rfc-implied-type-for-patterns-in-argument-position/12391 https://internals.rust-lang.org/t/pre-rfc-implied-type-for-p... [3]: https://internals.rust-lang.org/t/pre-rfc-anonymous-struct-and-union-types/3894 https://internals.rust-lang.org/t/pre-rfc-anonymous-struct-a...