DEV Community

Jesse Phillips
Jesse Phillips

Posted on

4

Boolean in D

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
Enter fullscreen mode Exit fullscreen mode

D utilize lower case true/false.

It will also treat 0 or null as false.

string str;
if(str) // false, str is null
Enter fullscreen mode Exit fullscreen mode

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 "" 
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more