#Confusion about captures

1 messages · Page 1 of 1 (latest)

hot lion
#

So assuming this following snippet:

var my_var: ?SomeType = ...;
...
if (my_var) |captured| {
  ...
}

Why is "captured" const here unless I do:

var my_var: ?SomeType = ...;
...
if (my_var) |*captured| {
  ...
}

I'm confused because I don't understand why I need to capture a pointer to "captured" in order to be able to modify it.

I'd understand if it was:

const my_var: ?SomeType = ...

Because here "my_var" is const, so I'd understand the need to capture a pointer

simple phoenix
#

*captured is capturing a pointer to the non-null part of my_var, so modifying it is modifying my_var itself. if you want captured to be a mutable copy youd have to make a temp var like |captured_const| { var captured = captured_const; …

captures are const by default the same reason parameters are, prevents some bugs and iirc helps optimization

formal ravine
hot lion
simple phoenix
hot lion