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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

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

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay