Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 67e5f0d8b5
Fetching contributors…

Cannot retrieve contributors at this time

572 lines (490 sloc) 18.13 kb
$(D_S D Programming Language,
$(SECTION3 The D programming language. Modern
convenience. Modeling power. Native efficiency.,
function showHideYourCodeHere()
var obj = document.getElementById('your-code-info');
}else{ = 'block';
// Computes average line length for standard input.
import std.stdio;
void main() {
ulong lines = 0;
double sumLength = 0;
foreach (line; stdin.byLine()) {
sumLength += line.length;
writeln("Average line length: ",
lines ? sumLength / lines : 0);
<div style="font-size:75%;text-align:right;position:relative;top:-3em;right:0.5em;bottom:0em;cursor:pointer;" onclick='showHideYourCodeHere();'><a id="your-code-link">[your code here]</a></div>
$(TAG2 div, id="your-code-info" style="display:block; position:relative; width: 50%; margin-left:auto; top:-2.5em; bottom:0em; background:white; border:1px solid #ccc; font-size:80%; padding:0px 5px 0px 5px; line-height:1.4em;",
Got a brief example illustrating D? Submit your code to the
$(LINK2, digitalmars.D forum)$(COMMA)
specifying <span class="nobr">"[your code here]"</span> in the title. Upon approval$(COMMA) it will be showcased
on a random schedule on D&#145;s homepage.
D is a language with C-like syntax and static typing. It pragmatically combines
efficiency, control, and modeling power, with safety and programmer productivity.
$(SECTION3 Convenience,
$(LI D allows writing large code fragments without redundantly specifying types,
in the style of dynamic languages. Yet static inference deduces types and other
code properties, giving the best of both the static and the
dynamic worlds. $(EXAMPLE 1,
void main() {
// Define an array of numbers, double[]. Compiler recognizes the common
// type of all initializers.
auto arr = [ 1, 2, 3.14, 5.1, 6 ];
// Dictionary that maps string to int, type is spelled int[string]
auto dictionary = [ "one" : 1, "two" : 2, "three" : 3 ];
// Calls the min function defined below
auto x = min(arr[0], dictionary["two"]);
// Type deduction works for function results. This is important for generic
// functions, such as min below, which works correctly for all comparable
// types.
auto min(T1, T2)(T1 lhs, T2 rhs) {
return rhs < lhs ? rhs : lhs;
$(LI Automatic memory management makes for safe, simple, and robust code.
D also supports scoped resource management (aka the
$(WEB, RAII) idiom)
and $(LINK2 statement.html#ScopeGuardStatement, $(D scope) statements) for
deterministic transactional code that is easy to write and read. $(EXAMPLE 2,
import std.stdio;
class Widget { ... }
void main() {
// Automatically managed.
auto w = new Widget;
// Code is executed in any case upon scope exit.
scope(exit) { writeln("Exiting main."); }
// File is closed deterministically at scope's end.
foreach (line; File("text.txt").byLine()) {
$(LI Built-in linear and associative arrays, slices, and ranges make daily
programming simple and pleasant for tasks small and large. $(EXAMPLE 3,
import std.range, std.stdio;
// Compute average line length for stdin
void main() {
ulong lines = 0, sumLength = 0;
foreach (line; stdin.byLine()) {
sumLength += line.length;
writeln("Average line length: ",
lines ? cast(double) sumLength / lines : 0.0);
$(SECTION3 Power,
$(LI The best paradigm is to not impose one at the expense of others.
D offers classic polymorphism, value semantics, functional
style, generics, generative programming, contract programming,
and more&mdash;all harmoniously integrated. $(EXAMPLE 4,
// Interfaces and classes
interface Printable {
void print(uint level)
in { assert(level > 0); } // contract is part of the interface
// Interface implementation
class Widget : Printable {
void print(uint level) { ... }
// Single inheritance of state
class ExtendedWidget : Widget {
override void print(uint level)
in { /* weakening precondition is okay */ }
body {
... level may be 0 here ...
// Immutable data shared across threads
immutable string programName = "demo";
// Mutable data is thread-local
int perThread = 42;
// Explicitly shared data
shared int perApp = 5;
// Structs have value semantics
struct BigNum {
// intercept copying
this(this) { ... }
// intercept destructor
~this() { ... }
$(LI D offers an innovative approach to concurrency featuring true
immutable data, message passing, no sharing by default, and
controlled mutable sharing across threads. $(WEBX,
$(LI From simple scripts to large projects, D has the breadth
to scale with any application's needs: unit testing,
information hiding, refined modularity, fast compilation, precise
interfaces. $(WEBX,
$(SECTION3 Efficiency,
$(LI D compiles naturally to efficient native code.)
$(LI D is designed such that most "obvious" code is fast $(I and)
safe. On occasion a function might need to escape the confines of type
safety for ultimate speed and control. For such rare cases D offers
native pointers, type casts, access to any C function without any
intervening translation, and even inline assembler. $(EXAMPLE 5,
void livingDangerously() {
// Access to C's malloc and free primitives
auto buf = malloc(1024 * 1024);
scope(exit) free(buf); // free automatically upon scope exit
// Interprets memory as an array of floats
auto floats = cast(float[]) buf[0 .. 1024 * 1024];
// Even stack allocation is possible
auto moreBuf = alloca(4096 * 100);
// Using inline asm for extra speed on x86
uint checked_multiply(uint x, uint y) {
uint result;
version (D_InlineAsm_X86) {
// Inline assembler "sees" D variables.
asm {
mov EAX,x ;
mul EAX,y ;
mov result,EAX ;
jc Loverflow ;
return result;
} else {
result = x * y;
if (!y || x <= uint.max / y)
return result;
throw new Exception("multiply overflow");
$(LI The $(D @safe), $(D @trusted), and $(D @system) modular
attributes allow the programmer to best decide the safety/efficiency
tradeoffs of a particular application, and have the compiler check for
consistency. $(LINK2 safed.html,
$(XXXXSECTION2 Community,
$(P D is the center of a growing, vibrant community. Get D-related
news from the $(D digitalmars.D.announce) forum $(TAG2 span,
style="font-size:80%", $(WEB,
[browse]) $(LINK2 news://,
[usenet]) $(WEB,
[mailing list])). On Twitter, subscribe to D's official announcements
channel, $(WEB!/D_Programming,@D_Programming), and
search for (and disseminate) news using tag $(WEB!/search/%23d_lang, #d_lang).)
$(P Learning D and have a question about the best way to do X? The $(D
digitalmars.D.learn) forum $(TAG2 span, style="font-size:80%", $(WEB,
[browse]) $(LINK2 news://,
[usenet]) $(WEB,
[mailing list])) is the hangout place where many D experts are ready
to help fellow hackers.)
$(P The $(D digitalmars.D) forum $(TAG2 span, style="font-size:80%",
[browse]) $(LINK2 news://, [usenet])
[mailing list])) is the best place to discuss anything and everything
related to D: language design ideas, suggestions, status and future,
contributions to the language and its standard library. Reach and
engage all major D contributors, including the very creator of D,
$(WEB, Walter Bright). For real-time conversation, use #d IRC channel on freenode.)
$(SECTION3 To contribute,
$(P Many D enthusiasts are not only using, but also contributing to
the language, its implementation, and its standard library. The main
hub of D development is $(WEB,
D-Programming-Language on github). The project has been awash in
contributions ever since creating the github repository on January 23,
2011, with an average of over 3 pull requests per day. (That doesn't
mean there's not a lot more to do!) You are welcome to fork any
subproject ($(WEB, compiler),
$(WEB, runtime), $(WEB, standard library), $(WEB,
website), $(WEB, tools), or
$(WEB, installer)), change
it in useful ways, and propose your changes back to the community.
$(P The reference compiler $(LINK2 download.html, dmd) has inspired
work on alternate implementations that add value by using distinct
$(LI GNU D compiler $(LINK2, gdc).)
$(LI LLVM D Compiler $(WEB, ldc).)
$(P The gdc compiler is of particular interest because it taps into
gcc's extremely portable back-end and large installation base. The D
development team has signed the appropriate documents with FSF and is
pursuing integration of gdc with gcc version 4.8 starting March 2012.
$(WEB, Iain Buclaw) is leading that
$(COMMENT $(AMAZONLINK 0321635361, <img style="float:right;
padding-left:1.5em; padding-bottom:1.5em; border-width: 0;"
src="images/tdpl.jpg" alt="The D Programming Language book" />))
$(P The K&amp;R of D is here! Get $(AMAZONLINK 0321635361, The D
Programming Language) by Andrei Alexandrescu&mdash;the authoritative
source on everything D. From the book's introduction:
$(BLOCKQUOTE $(AMAZONLINK 0321635361, The D Programming Language) by
Andrei Alexandrescu, D is a language that attempts to consistently do
the right thing within the constraints it chose: system-level access
to computing resources, high performance, and syntactic similarity
with C-derived languages. In trying to do the right thing, D
sometimes stays with tradition and does what other languages do, and
other times it breaks tradition with a fresh, innovative solution. On
occasion that meant revisiting the very constraints that D ostensibly
embraced. For example, large program fragments or indeed entire
programs can be written in a well-defined memory-safe subset of D,
which entails giving away a small amount of system-level access for a
large gain in program debuggability.))
$(P D is a multi-paradigm programming language that combines a
principled approach with a focus on practicality. In D you get to
harness the power and high performance of C and C++ and also the
safety and programmer productivity of modern languages such as Ruby
and Python. Special attention is given to the needs of quality
assurance, documentation, portability, and reliability.)
$(P The D language is statically typed and compiles directly to machine code.
It&rsquo;s multiparadigm, supporting many programming styles:
imperative, object oriented, and metaprogramming. It&rsquo;s a member of the C
syntax family, and its appearance is very similar to that of C++.
Here&rsquo;s a quick list of $(LINK2 comparison.html, features).
$(P This site does not refer to the first edition of the language,
known as "D version 1" or "D1". Currently, D1 is in maintenance mode
and has documentation available $(LINK2,here). We recommend the
current edition of the D programming language (formerly known as "D2")
for new projects. )
$(P There are currently three implementations:
$(LI Digital Mars dmd for
$(LINK2 dmd-windows.html, Windows),
$(LINK2 dmd-linux.html, x86 Linux),
$(LINK2 dmd-osx.html, Mac OS X), and
$(LINK2 dmd-freebsd.html, x86 FreeBSD).
$(LI LLVM D Compiler $(LINK2, ldc).
$(LI Gnu D compiler $(LINK2, gdc)
for several platforms, including
$(LINK2, Windows) and
$(LINK2, Mac OS X)
for D versions 1.030 and 2.014.
$(LI Gnu D compiler $(LINK2, gdc).
$(COMMENT $(LINK2, D.NET compiler)
alpha for .NET for D version 2.)
$(P A large and growing collection of D source code and projects
are at $(LINK2, dsource).
More links to innumerable D wikis, libraries, tools, media articles,
etc. are at $(LINK2, dlinks).
This document is available as a
$(LINK2, pdf),
as well as in
$(LINK2, Japanese)
$(LINK2, Portugese)
A German book
$(LINK2, Programming in D: Introduction to the new Programming Language)
is available, as well as
a Japanese book
$(LINK2, D Language Perfect Guide),
and a Turkish book
$(LINK2, D Programlama Dili Dersleri).
$(COMMENT: Japanese by Kazuhiro Inaba, Portugese by Christian Hartung)
$(P This is an example D program illustrating some of the capabilities:)
/* shebang is supported */
/* Hello World in D
To compile:
dmd hello.d (or on Unix just make hello.d executable and run it)
or to optimize:
dmd -O -inline -release hello.d
import std.stdio;
void main(string[] args)
$(V1 writefln("Hello World, Reloaded");)$(V2 writeln("Hello World, Reloaded");)
// auto type inference and built-in foreach
foreach (argc, argv; args)
// Object Oriented Programming
auto cl = new CmdLin(argc, argv);
// Improved typesafe printf
writeln(cl.argnum, cl.suffix, " arg: ", cl.argv);
// Automatic or explicit memory management
delete cl;
// Nested structs and classes
struct specs
// all members automatically initialized
size_t count, allocated;
// Nested functions can refer to outer
// variables like args
specs argspecs()
specs* s = new specs;
// no need for '->'
s.count = args.length; // get length of array with .length
s.allocated = typeof(args).sizeof; // built-in native type properties
foreach (argv; args)
s.allocated += argv.length * typeof(argv[0]).sizeof;
return *s;
// built-in string and common string operations
writefln("argc = %d, " ~ "allocated = %d",
argspecs().count, argspecs().allocated);
class CmdLin
private size_t _argc;
private string _argv;
this(size_t argc, string argv) // constructor
_argc = argc;
_argv = argv;
size_t argnum()
return _argc + 1;
string argv()
return _argv;
string suffix()
string suffix = "th";
switch (_argc)
case 0:
suffix = "st";
case 1:
suffix = "nd";
case 2:
suffix = "rd";
return suffix;
$(P $(B Notice:) We welcome feedback about the D compiler or language, but please be explicit about
any claims to intellectual property rights with a copyright or patent notice if you have such for
your contributions. We want D to remain open and free to use, and do not wish to be caught by
someone posting a patch to the compiler, and then later claim compensation for that work.)
TAG2=<$1 $2>$3</$1>
WEB=$(LINK2 http://$1,$2)
WEBX=$(LINK2 http://$1,$2)
D=<span class="d_inlinecode">$0</span>
document.write('$(TAG2 div, id="q$1" class="question" onclick="showHideAnswer(this);", <span class="nobr">See example.</span>)');
<noscript><span class="nobr">See example.</span></noscript>
$(TAG2 div, id="a$1" class="answer-nojs", $2)
<div id="navigation">
<div id="twitter">
<script src=""></script>
new TWTR.Widget({
version : 2,
type : 'profile',
rpp : 8,
interval : 30000,
width : 'auto',
height : 600,
theme : {
shell : {
background : '#1f252b',
//color : '#000000'
tweets : {
//background : '',
//color : '',
//links : ''
features : {
scrollbar : true,
loop : false,
live : true,
behavior : 'all'
<div id="content" style="margin-right:18em;" class='hyphenate'>
Jump to Line
Something went wrong with that request. Please try again.