Unpacking Slices
jfondren
julian.fondren at gmail.com
Tue Jun 15 00:48:34 UTC 2021
On Monday, 14 June 2021 at 18:08:27 UTC, Justin Choi wrote:
> Is there any shortcut for unpacking slices like I'd want to do
> in a scenario like this?
> `info = readln.strip.split;`
> `string a = info[0], b = info[1], c = info[2];`
This doesn't leave you with multiple local variables, but it
leaves
you with names instead of numbers for the members of the slice:
```d
import std.stdio, std.typecons, std.algorithm, std.array,
std.conv, std.range;
auto tuple(string rawnames, T)(T[] vals) {
const names = rawnames.splitter(' ').array;
assert(names.length == vals.length, "wrong # params to
tuple()");
mixin("auto ret = Tuple!("
~ names.map!(n => T.stringof ~ `, "` ~ n ~
`"`).joiner(", ").array
~ ")("
~ names.length.iota.map!(i => "vals[" ~ i.to!string ~
"]").joiner(", ").array
~ ");");
return ret;
}
void main() {
int[] x = [1,2,3];
auto tup = tuple!"a b c"(x);
writeln(tup.b);
}
```
More information about the Digitalmars-d-learn
mailing list