I recently got to work outside my comfort zone, rather than scripting in D I was to utilize Python. It has been a long time since programming in Python, I've developed a style and Python does not follow C syntactic choices. Thus I had to search on how to solve problems I already know in D. I thought it would make for an opportunity to answer those types of questions for D.
My need to specify a boolean value seemed like a good place to start.
bool variable = true;// false
D utilize lower case true/false.
It will also treat 0 or null as false.
string str;
if(str) // false, str is null
Strings are special in that null or empty likely need similar logic paths. In D the following works with all arrays (string is an array)
import std.range;
string str;
if(str.empty) // null or ""
D has custom types with operator overloading, so such a post is not complete without mentioning it.
Classes can't override boolean and is only checking if the reference is null. However struct being a value type allow for changing behavior with opCast
if (e) => if (e.opCast!(bool))
if (!e) => if (!e.opCast!(bool))
https://dlang.org/spec/operatoroverloading.html#boolean_operators
D's operator overloading relies on its powerful template system. That is out of scope for this article.
Top comments (0)