D is a general-purpose programming language with static typing, systems-level access, and C-like syntax. With theD Programming Language, write fast, read fast, and run fast.
Fast code, fast.
Got a brief example illustrating D?
Submit your code to the digitalmars.D forum specifying "[your code here]" in the subject.
Upon approval it will be showcased here on a random schedule.
The D programming languageModern convenience.Modeling power.Native efficiency.void main(){import std.range, std.stdio;auto sum = 0.0;auto count = stdin//Get an input range set up to read one line at a time .byLine//Perform a transparent operation (as in the shell command tee) .tee!(l => sum += l.length) .walkLength; writeln("Average line length: ", count ? sum / count : 0);}
2.4 plus 2.4 equals 5 for sufficiently large values of 2.import std.algorithm, std.conv, std.functional, std.math, std.regex, std.stdio;alias round = pipe!(to!real, std.math.round, to!string);static reFloatingPoint = ctRegex!`[0-9]+\.[0-9]+`;void main(){// Replace anything that looks like a real// number with the rounded equivalent. stdin .byLine .map!(l => l.replaceAll!(c => c.hit.round) (reFloatingPoint)) .each!writeln;}
MercuryVenusEarthMarsJupiterSaturnUranusNeptuneimport std.stdio, std.array, std.algorithm;void main(){ stdin .byLineCopy .array .sort!((a, b) => a > b)// descending order .each!writeln;}
void main(){import std.algorithm, std.stdio;"Starting program".writeln;enum a = [ 3, 1, 2, 4, 0 ];// Sort data at compile-timestaticimmutable b = sort(a);// Print the result _during_ compilationpragma(msg,"Finished compilation: ", b);}
void main(){import std.exception, std.stdio, std.process;auto result = ["whoami"].execute; enforce(result.status == 0); result.output.write;}
void main(){import std.algorithm, std.stdio, std.file, std.range;enum cols = 14;// Split file into 14-byte chunks per row thisExePath.File("rb").byChunk(cols).take(20).each!(chunk =>// Use range formatting to format the// hexadecimal part and align the text part writefln!"%(%02X %)%*s %s"( chunk, 3 * (cols - chunk.length),"",// Padding chunk.map!(c =>// Replace non-printable c < 0x20 || c > 0x7E ? '.' :char(c))));}
#!/usr/bin/env dub/+ dub.sdl:dependency "vibe-d" version="~>0.9.0"+/void main(){import vibe.d; listenHTTP(":8080", (req, res) { res.writeBody("Hello, World: " ~ req.path); }); runApplication();}
void main(){import std.datetime.stopwatch : benchmark;import std.math, std.parallelism, std.stdio;auto logs =newdouble[100_000];auto bm = benchmark!({foreach (i,ref elem; logs) elem = log(1.0 + i); }, {foreach (i,ref elem; logs.parallel) elem = log(1.0 + i); })(100);// number of executions of each tested function writefln("Linear init: %s msecs", bm[0].total!"msecs"); writefln("Parallel init: %s msecs", bm[1].total!"msecs");}
void main(){import std.stdio : writefln;import std.algorithm.sorting : sort;import std.range : chain;int[] arr1 = [4, 9, 7];int[] arr2 = [5, 2, 1, 10];int[] arr3 = [6, 8, 3];// @nogc functions are guaranteed by the compiler// to be without any GC allocation () @nogc { sort(chain(arr1, arr2, arr3)); }(); writefln("%s\n%s\n%s\n", arr1, arr2, arr3);}
void main(){import std.stdio : writefln;// An associative array mapping pairs of characters to integersint[char[2]] aa;auto arr ="ABBBA";// Iterate over all pairs in the string// ['A', 'B'], ['B', 'B'], ..., ['B', 'A']foreach (i; 0 .. arr.length - 1) {// String slicing doesn't allocate a copychar[2] pair = arr[i .. i + 2];// count occurrences aa[pair]++; }foreach (key, value; aa) writefln("key: %s, value: %d", key, value);}
2 3 3 4 + * *void main(){import std.stdio, std.string, std.algorithm, std.conv;// arr is real[] and sym is the current symbol readln.split.fold!((arr, sym) {staticforeach (c;"+-*/")if (sym == [c])// replace the last 2 elements with the binary opreturn arr[0 .. $-2] ~mixin("arr[$-2] " ~ c ~" arr[$-1]");// sym must be a numberreturn arr ~ sym.to!real; })((real[]).init).writeln;}
struct Point{privatedouble[2] p;// Forward all undefined symbols to palias pthis;double dot(Point rhs) {return p[0] * rhs.p[0] + p[1] * rhs.p[1]; }}void main(){import std.stdio : writeln;// Point behaves like a `double[2]` ... Point p1, p2; p1 = [2, 1], p2 = [1, 1];assert(p1[$ - 1] == 1);// ... but with extended functionality writeln("p1 dot p2 = ", p1.dot(p2));}
D is made possible through the hard work and dedication of many volunteers, with the coordination and outreach of the D Language Foundation, a 501(c)(3) non-profit organization. You can help further the development of the D language and help grow our community by supporting the Foundation.
DonateLearn More About The Foundation
Lots of to oursponsors andcontributors.
Stay updated with the latest posts in theOfficial D Blog from February 22, 2024:DMD Compiler as a Library: A Call to Arms by Razvan Nitu.
From October 2, 2023:Crafting Self-Evident Code with D by Walter Bright.
Take the Tour, exploremajor features in D, browse thequick overview, start withC orC++ background, and ask questions in the Learn forum.
For a deeper dive into D check outbooks orvideos such as Ali Çehreli's free bookProgramming in D.
Discuss D on theforums, join theIRC channel, read ourofficial Blog, or follow us onTwitter. Browse thewiki, where among other things you can find thehigh-level vision of theD Language Foundation.
Refer to thelanguage specification and the documentation ofPhobos, D's standard library. TheDMD manual tells you how to use the compiler. Readvarious articles to deepen your understanding.
Report any bugs you find to our bug tracker. If you can fix an issue, make a pull request onGitHub. There aremany other ways to help, too!
DUB is the package manager for D. Get started with DUB, and check out theavailable packages.
Configure linting, formatting or completion for your favoriteIDE,editor or userun.dlang.io to play and experiment with D code.
Learn aboutpragmatic D, theDStyle,common D idioms andtemplates, See what's coming upcoming withnext version, exploreD Improvement Proposals, and don't fearD's garbage collection.
D allows writing large code fragments without redundantly specifying types,like dynamic languages do. On the other hand, static inference deduces types and othercode properties, giving the best of both the static and thedynamic worlds.
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 belowauto 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;}
Automatic memory management makes for safe, simple, and robust code.D also supports scoped resource management (aka theRAII idiom)andscope statements fordeterministic transactional code that is easy to write and read.
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(__FILE_FULL_PATH__).byLine()) { writeln(line); } writeln();}
Built-in linear and associative arrays, slices, and ranges make dailyprogramming simple and pleasant for tasks, both small and large.
The D programming languageModern convenience.Modeling power.Native efficiency.// Compute average line length for stdinvoid main(){import std.range, std.stdio;auto sum = 0.0;auto count = stdin.byLine .tee!(l => sum += l.length).walkLength; writeln("Average line length: ", count ? sum / count : 0);}
The best paradigm is to not impose something at the expense of others.D offers classic polymorphism, value semantics, functionalstyle, generics, generative programming, contract programming,and more—all harmoniously integrated.
// Interfaces and classesinterface Printable{void print(uint level)// contract is part of the interfacein {assert(level > 0); }}// Interface implementationclass Widget : Printable{void print(uint level)in{ }do{ }}// Single inheritance of stateclass ExtendedWidget : Widget{overridevoid print(uint level)in {/* weakening precondition is okay */ }do {//... level may be 0 here ... }}// Immutable data shared across threadsimmutable string programName ="demo";// Mutable data is thread-localint perThread = 42;// Explicitly shared datasharedint perApp = 5;// Structs have value semanticsstruct BigNum{// intercept copyingthis(this) { }// intercept destructor ~this() { }}void main(){// ...}
D offers an innovative approach to concurrency, featuring trueimmutable data, message passing, no sharing by default, andcontrolled mutable sharing across threads.Read more.
From simple scripts to large projects, D has the breadthto scale with any application's needs: unit testing,information hiding, refined modularity, fast compilation, preciseinterfaces.Read more.
D compiles naturally to efficient native code.
D is designed such that most "obvious" code is fastandsafe. On occasion a function might need to escape the confines of typesafety for ultimate speed and control. For such rare cases D offersnative pointers, type casts, access to any C function without anyintervening translation, manual memory management, custom allocatorsand even inline assembly code.
import core.stdc.stdlib;void livingDangerously(){// Access to C's malloc and free primitivesenum bytes =float.sizeof * 1024 * 1024;auto buf = malloc(bytes);// free automatically upon scope exitscope(exit) free(buf);// Interprets memory as an array of floatsauto floats =cast(float[]) buf[0 .. bytes];// Even stack allocation is possibleauto moreBuf = alloca(4096 * 100);//...}// Using inline asm for extra speed on x86uint checked_multiply(uint x,uint y){uint result;version (D_InlineAsm_X86) {// Inline assembler "sees" D variables and labels.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; }Loverflow:thrownew Exception("multiply overflow");}void main(){// ...}
The@safe,@trusted, and@system functionattributes allow the programmer to best decide the safety-efficiencytradeoffs of an application, and have the compiler check forconsistency.Read more.