DLang Notes and Examples
← prev | next →     Top-level ToC     /language-basics.html     (printable version)

D source:

  • statically-typed, lexically-scoped, block-structured
  • curlies, and semicolons
  • // single-line comment
  • /// single-line doc comment
  • /* multi-line comment */
  • /** multi-line doc comment, doesn't nest */   Doc comments document the thing under them.
  • /++ multi-line doc comment, *nests*. +/
  • identifiers are what you’d expect: fine, Good, _right, and __dont_you_dare.
  • a module == a .d file, and they live in “packages” (hierarchy for modules, corresponding to directory names).

When you import a module, the default is to get all its names imported into the current namespace:

import std.stdio;

void main() {
    // This name is from std.stdio.
    writeln("hi");
}

but don’t do that. Instead, do

import std.stdio: writeln;

// or, if you have name collisions, you could even do:
import stdio = std.stdio;
stdio.writeln(...);

Since D is statically-typed, you need to declare them with a type, unless you declare them auto, and the compiler infers the type.

int    i = 3;
long   j = 4_000_000_000;
double x = 5.5;
auto   y = 5.5; // type is inferred

for (int i = 0; i < 10; i++) {
    writeln(i);
}

auto arr = ["a", "b", "c"];
foreach (elem; arr) {
    writeln(elem);
}

int n = 0;
while (n < 10) {
    writeln(n);
    n++;
}

do {
    //...
} while (n < 10);

foreach (i; 5..10) {
    writeln(i);
}

D supports uniform function call syntax (UFCS). That is, if the compiler sees:

c.foo(x);

and foo is not a member of class C, then the compiler looks for a free function of the form:

foo(c, x);
long[] ell; // dynamic (resizable) array
long[5] yo; // static array (can't change its size)

if (...) {

} else if (...) {

} else if (...) {

} else {
    //...
}

foreach (x; ell) {
    // Each `x` is a copy of elems in `ell`.
}

foreach (ref x; ell) {
    // Each `x` now refers to each elem in `ell`.
}

switch (foo) {
    case "x":
        writeln("It was x.");
        break; // Need this, otherwise falls through.
    case "y":
        //...
        break;

}