he_the_great (he_the_great) wrote,
he_the_great
he_the_great

Boolean in D

Find the complete Series: https://dev.to/jessekphillips/boolean-in-d-943

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.

```dlang
bool variable = true;// false
```

D utilize lower case true/false.

It will also treat 0 or null as false.

```dlang
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)

```dlang
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`

```dlang
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.
Tags: dlang, tutorial
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments