Skip to content
Lesson 2 of 7

Step 1 of 5 · Reading · ~1 min

Learn

Basics

D is statically typed but supports rich inference:

int age = 36;
string name = "Ada";
double pi = 3.14159;
bool active = true;

auto inferred = 42;     // int
auto greeting = "hi";   // string

Numeric types: byte, short, int, long (signed), ubyteulong (unsigned), float, double, real (extended precision).

Reading typed input from stdin uses readf:

import std.stdio;
int a, b;
readf("%d %d", &a, &b);
writeln(a + b);

For reading line-by-line and parsing yourself:

import std.conv : to;
import std.string : chomp;
int n = readln().chomp.to!int;

to!Type is D's templated conversion — clean and type-safe.

Constants: const, immutable, enum

Three ways to say "this does not change", and they are not interchangeable:

enum LIMIT = 100;               // manifest constant: substituted at compile time,
                                // no variable exists at run time
immutable double PI = 3.14159;  // a real variable, never changes, transitively
const int[] view = someArray;   // *this reference* will not mutate the data

Reach for enum when the value is a fixed number you already know while compiling, immutable when a value must stay constant for the whole program, and const when you are only promising not to modify something through this particular name.

Up nextFunctionsFunctions and Ranges

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…