This Week in D September 11, 2016

Welcome to This Week in D! Each week, we'll summarize what's been going on in the D community and write brief advice columns to help you get the most out of the D Programming Language.

The D Programming Language is a general purpose programming language that offers modern convenience, modeling power, and native efficiency with a familiar C-style syntax.

This Week in D has an RSS feed.

This Week in D is edited by Adam D. Ruppe. Contact me with any questions, comments, or contributions.

Statistics

In the community

Community announcements

See more at the announce forum.

Tip of the Week

Never name anything init. The language will allow it, but you'll get random breakage that is a pain to debug unless you have some idea where to look.

All types in D have a built in property called init that returns the initial value for it. However, this is not a keyword so there is nothing preventing you from defining your own member with the name... which breaks all the code that expects item.init to return the built in value. Among the things that make this assumption is std.range.. which is used heavily throughout Phobos.

If you do this wrong, you will get bizarre errors. Try compiling this, with and without the init method commented:

import std.array;

struct Test {
        int front;
        void popFront() {}
        bool empty() { return true; }
        void init() {}
}

void main() {
        Test test;
        int[] arr = test.array;
}

With init, it gives:

iii.d(12): Error: template std.array.array cannot deduce function from argument types !()(Test), candidates are:
/home/me/d/dmd2/linux/bin32/../../src/phobos/std/array.d(97):        std.array.array(Range)(Range r) if (isIterable!Range && !isNarrowString!Range && !isInfinite!Range)
/home/me/d/dmd2/linux/bin32/../../src/phobos/std/array.d(199):        std.array.array(String)(String str) if (isNarrowString!String)

Without init, it compiles normally - we have a plain input range and Phobos recognizes it as such. But with init, it fails... because isInputRange happens to be implemented in terms of is(typeof(T.init)). Internal implementation gives random external failure, all because there's a seemingly innocuous method called init on the type.

So just take my advice and pretend init is a keyword and never use it. It will end in misery otherwise.

Learn more about D

To learn more about D and what's happening in D: