Skip to content

Instantly share code, notes, and snippets.

@Biotronic
Last active Aug 27, 2018
Embed
What would you like to do?
Null-coalescing operator in D
struct NullCoalesce {
static auto opBinaryRight(string op : "|", T)(T lhs) {
return NullCoalesceImpl!T(lhs);
}
}
alias NullCoalesce nil;
struct NullCoalesceImpl(T) {
T value;
auto opBinary(string op = "|", R)(lazy R rhs) {
if (value is null) return rhs;
return value;
}
}
unittest {
int* a = null;
int b = 3;
assert(*(a |nil| &b) == 3);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment