object destructuring
See original GitHub issueUsing the techniques from #4127 and #4406. It’s now possible to implement destructuring for user-written classes as a syntax sugar over existing constructs in the language. (That is to say, with zero impact upon the backend.)
For example, we could make:
case (Person(name, age)) expr
desugar to:
case (is Person) let ([name, age] = p.destructured) expr
Given a new language module interface Struct
shown here.
Or, alternatively, we could make:
case (Person { name, age }) expr
desugar to:
case (is Person) let (name = p.name, age = p.age) expr
Which is a solution that requires no Struct
interface or any other kind of “extractor” function, but does not allow easy renaming. (You would have to write Person { fullName=name, age }
or whatever if you were fussy about local aliases.)
I have two questions about this:
-
Which of the above approaches do we prefer? With or without the
Struct
interface? I lean towards the solution without it. -
What does destructuring look like in syntactic locations other than
switch
? Is it, for example:for (Person {name, age} in people) { ... }
Or would it just be:
for ({name, age} in people) { ... }
Thoughts?
Issue Analytics
- State:
- Created 7 years ago
- Comments:25 (23 by maintainers)
Top GitHub Comments
Ah no, sorry, my bad. That was silly. You would write it like this:
or like this:
which is perfectly natural, and totally consistent with the syntax for aliases.
So that’s fine. There’s no problem there for nested patterns.
For literals in patterns I guess you would come up with something like:
which is also OK, I suppose.
@gavinking - Agree the first one feels very natural.
I think the following syntax for combining all of destructuring, conditions and aliasing would feel as natural, without being inconsistent with existing syntaxes:
My head naturally parses the
{ ... }
part ofaddress { street, city, state }
as simply a destructing operator/operation onaddress
, more than as a local declaration ofstreet
,city
andstate
. It just happens that the destructuring has the effect of creating the locals anyway.So that it really doesn’t feel in conflict with the syntax for conditions:
(exists localName = expression)
import some.package { TypeAlias = Type }
Without aliases:
Without conditions (similar to imports):
Without aliases or conditions: