user-experience icon indicating copy to clipboard operation
user-experience copied to clipboard

Destructuring assignment for object

Open iacore opened this issue 3 years ago • 4 comments

Currently there is no way to destruct object on assignment.

my (:$key, :$value) = a => 1; # not what you think
# $key is :a(1)
# $value is (Any)

This is weird, since destructing array works both in block signature and in assignment.

iacore avatar Jun 20 '22 14:06 iacore

In Raku, destructuring is performed by binding (thus "signature binding"):

my (:$key, :$value) := a => 1;
say $key; # a
say $value; # 1

jnthn avatar Jun 20 '22 14:06 jnthn

But how is ths usable?

my ($a, $b) = 1, 2

I don't remember this documented, but := is much better (to catch errors):

my ($a, $b) := 1, 2, 3;

Too many positionals passed to '<unit>'; expected 2 arguments but got 3
  in block <unit> at <unknown file> line 1

iacore avatar Jun 20 '22 19:06 iacore

But how is ths usable?

my ($a, $b) = 1, 2

That's list assignment. I suggest looking up some docs on assignment vs binding; Raku offers both, and they are quite different in nature.

jnthn avatar Jun 20 '22 20:06 jnthn

The official docs (docs.raku.org) only has example for single-value binding (my $a = $b). Now I understand it better.

iacore avatar Jun 21 '22 06:06 iacore