how to assign multiple variables at once by unpacking array?

bachmeier no at spam.net
Sat Oct 7 11:35:05 UTC 2023


On Saturday, 7 October 2023 at 07:31:45 UTC, mw wrote:
> https://stackoverflow.com/questions/47046850/is-there-any-way-to-assign-multiple-variable-at-once-with-dlang
>
> How to do this Python code in D:
>
> ```
>>>> s = "1 2 3"
>>>> A,B,C = map(int, s.split(" "))
>>>> A,B,C
> (1, 2, 3)
>
> ```
>
> Is there a better way (since 2017)?

That functionality exists, you just have to put things in 
different places, but there are no more keystrokes:

```
import std;

void main() {
     int x;
     double y;
     string z;

     foo(x, y, z);
     writeln(x);
     writeln(y);
     writeln(z);
}

void foo(ref int x, ref double y, ref string z) {
     x = 4;
     y = 2.6;
     z = "hello world";
}
```

Maybe there is an argument for `x, y, z = foo();` but it's not 
that it's easier to read or write. If the goal is to not have to 
specify the types of the variables, it's hard for me to see the 
advantage of

```
auto x, y, z = foo();
```

over returning a struct.


More information about the Digitalmars-d-learn mailing list