Skip to content

Instantly share code, notes, and snippets.

@valmat
Last active February 20, 2018 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valmat/bdcf24e3365d202aaae7db6ffbf9429d to your computer and use it in GitHub Desktop.
Save valmat/bdcf24e3365d202aaae7db6ffbf9429d to your computer and use it in GitHub Desktop.
variable destructuring; array to variables list; destructuring assign.
module StringManip;
import std.range : empty, popFront, front;
auto destr(Arg0, Args...)(ref Arg0 arg0, ref Args args)
{
return DestrInstance!(Arg0, Args.length+1)(arg0, args);
}
private struct DestrInstance(T, size_t N)
{
this(Args...)(ref T arg0, ref Args args)
{
items[0] = &arg0;
foreach(i, ref arg; args) {
items[i+1] = &arg;
}
}
// overloading assignment operator
void opAssign(rhs_t)(rhs_t rhs)
{
for (size_t i = 0; !rhs.empty && i < N; rhs.popFront(), ++i) {
*items[i] = rhs.front;
}
}
T* [N] items;
}
nothrow unittest {
string a, b, c;
destr(a,b,c) = ["foo1","foo2","foo3","foo4"];
assert([a,b,c] == ["foo1", "foo2", "foo3"]);
destr(a,b,c) = ["bar1","bar2"];
assert([a,b,c] == ["bar1", "bar2", "foo3"]);
}
@valmat
Copy link
Author

valmat commented Feb 13, 2018

@valmat
Copy link
Author

valmat commented Feb 20, 2018

I have written an other implementation that also can retrieve variables for iterable types and tuples:
https://gist.github.com/valmat/763c72465d7a1737229ae1c91393d629

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment