Before even thinking about this, I would point out that you can write a simple function:
import std.typecons; Tuple!(K, V) popitem(K, V)(ref V[K] arr) { foreach(k, v; arr) { arr.remove(k); return tuple(k, v); } throw new Exception("empty!"); } void main() { int[string] cool; cool["ten"] = 10; cool["twenty"] = 20; import std.stdio; writeln(cool.popitem()); writeln(cool.popitem()); }
Or using byKeyValue:
auto popitem(K, V)(ref V[K] arr) { foreach(item; arr.byKeyValue()) { arr.remove(item.key); return item; } throw new Exception("empty!"); } void main() { int[string] cool; cool["ten"] = 10; cool["twenty"] = 20; import std.stdio; auto item = cool.popitem(); writeln(item.key, item.value); item = cool.popitem(); writeln(item.key, item.value); }
In general, I like to encourage people not to be afraid to write their own functions. If you can express something with a few existing things, just write your own function, give it a name you like, and use it! With the syntax of uniform functions, you can easily even write extension methods for built-in types like I am here, and use it as if it were always there.
source share