Last active
August 27, 2018 07:59
-
-
Save Biotronic/ead12fb66da292244e9508cb2d2d0db0 to your computer and use it in GitHub Desktop.
Null-coalescing operator in D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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