"D"iving Into the D Programming Language
You know what's coming first, so without further ado:
importstd.stdio;voidmain() { writeln("Hello, world!"); }
Depending on other languages you know, you might have a feeling of déjà vu, a mild satisfaction that this little task doesn't already acquaint you with one third of the language's keywords, or perhaps a slight disappointment that D didn't go the scripting languages' route of allowing top-level statements. (Top-level statements invite global variables, which quickly turn into a liability as the program grows; D does offer ways of executing code outsidemain, just in a more structured manner.) If you're a stickler for precision, you'll be relieved to hear thatvoidmain相当于一个intmainthat returns “success” (code zero) to the operating system if it successfully finishes execution.
But let's not get ahead of ourselves. The purpose of the traditional “Hello, world” program is not to discuss a language's capabilities, but instead to get you started on writing and running programs using that language. So, after you typed the code above in a file called, say,hello.d
, fire a shell and type the following commands:
$ dmd hello.d $ ./hello Hello, world! $ _
where '$
' stands in for your favorite command prompt. If your operating system supports the so-called "shebang notation" for launching scripts, you'll be glad to hear that simply adding the line:
#!/usr/bin/rdmd
to the very beginning of yourhello.d
program makes it directly executable. After you operate that change, you can simply type at the command prompt:
$ chmod u+x hello.d $ ./hello.d Hello, world! $ _
(You only need to do thechmod
thing once.) Therdmd
program (part of the D distribution) is smart enough to cache the generated executable, such that compilation is actually done only after you've changed the program, not every time you run it. From here on, the short programs featured in this book won't specify this detail, leaving it up to you to use the shebang feature '#!' if you so prefer.
The program itself starts with the directive:
importstd.stdio;
which instructs the compiler to look for a module calledstd.stdioand make its symbols available for use.importis akin to the#includepreprocessor directive found in C and C++, but is closer in semantics to Python'simport: there is no textual inclusion taking place—just a symbol table acquisition. Repeatedimports of the same file are of no import.
Per the venerable tradition established by C, a D program consists of a collection of declarations spread across multiple files. The declarations can introduce, among other things, types, functions, and data. Our first program defines themainfunction to take no arguments and return "nothingness"—void, that is. When invoked,maincalls thewritelnfunction (which, of course, was cunningly defined by thestd.stdiomodule), passing it a constant string. The "ln
" suffix indicates thatwritelnappends a newline to the printed text.
Here are some resources for learning more about this topic:
- The D Programming Language
- OnSoftware(音频+视频):D编程朗uage with Andrei Alexandrescu
- Concurrency in the D Programming Language
The following sections provide a quick drive through Deeville. Little illustrative programs introduce basic language concepts. At this point the emphasis is on conveying a feel for the language, rather than giving pedantic definitions. If your eyes start glazing over some details, feel free to skip the tricky sections for now. Later chapters will treat each part of the language in greater detail, after which it's worth giving this chapter a more thorough pass.
1.1 Numbers and Expressions
Ever curious how tall foreigners are? Let's write a simple program that displays a range of usual heights in feet+inches and in centimeters.
/*Compute heights in centimeters for a range of heightsexpressed in feet and inches*/importstd.stdio;voidmain() {// values unlikely to change soonimmutableinchPerFoot = 12;immutablecmPerInch = 2.54;// loop'n writeforeach(feet; 5 .. 7) {foreach(inches; 0 .. inchPerFoot) { writeln(feet, "'", inches, "''\t", (feet * inchPerFoot + inches) * cmPerInch); } } }
When executed, this program will print a nice two-column list:
5'0'' 152.4 5'1'' 154.94 5'2'' 157.48 ... 6'10'' 208.28 6'11'' 210.82
Just like Java, C++, and C#, D supports/*multi-line comments*/and//single-line comments(plus a couple others, which we'll get to later). One more interesting detail is the way our little program introduces its data. First, there are two constants:
immutableinchperfoot = 12;immutablecmperinch = 2.54;
Constants that will never, ever change are introduced with the keywordimmutable. Constants, as well as variables, don't need to have a manifest type; the actual type can be inferred from the value with which the symbol is initialized. In this case, the literal12tells the compiler thatinchperfootis a 32-bit integer (denoted in D with the familiarint); similarly, the literal2.54causescmperinchto be a 64-bit floating-point constant (of typedouble). Going forth, we notice that the definitions offeetandinchesavail themselves of the same magic, because they look like variables all right, yet have no explicit type adornments. That doesn't make the program any less safe than one that stated:
immutable intinchperfoot = 12;immutable doublecmperinch = 2.54; ...foreach(intfeet; 5 .. 7) { ... }
and so on, only less redundant. The compiler allows omitting type declarations only when types can be unambiguously inferred from context. But now that types came up, let's pause for a minute and see what numeric types are available.
的顺序increasing size, the signed integral types includebyte,short,int, andlong,大小正好8、16、32、64位respectively. Each of these types has an unsigned counterpart of the same size, named following a simple rule:ubyte,ushort,uint, andulong. (There is no "unsigned" modifier as in C.) Floating point types consist offloat(32 bits IEEE-754 single-precision number),double(64 bits IEEE-754), andreal(which is as large as the machine's floating-point registers can go, but no less than 64 bits; for example, on Intel machinesrealis a so-called IEEE 754 double-extended 79-bit format). Automatic conversions among these types exist, with the restriction that an integral can never be automatically converted to one of fewer bits. However, floating-point numbers do allow automatic conversion to narrower floating-point numbers, decision that may seem surprising to the unwary. The explanation of this choice is a bit involved; the short version is that implicit narrowing conversions allow the compiler to manipulate intermediate calculation results at optimal size and precision, which ultimately means faster and more accurate floating-point calculations. The rule of thumb is that the compiler guarantees precisionat least as goodas required by the type specified in user code (i.e.,float,double, orreal). By giving the compiler the freedom to internally operate at higher precision, the pernicious effects of cumulative errors and intermediate overflows are greatly reduced.
Getting back to the sane realm of integral numbers, literals such as42can be assigned to any numeric type, with the mention that the compiler checks whether the target type is actually large enough to accommodate that value. So the declaration:
immutable byteinchperfoot = 12;
is as good as the one omittingbytebecause12fits as comfortably in 8 bits as in 32. By default, if the target type is to be deduced from the number (as in the sample program), integral constants have typeintand floating-point constants have typedouble.
Using these types, you can build a lot of expressions in D using arithmetic operators and functions. The operators and their precedence are much like the ones you'd find in D's sibling languages: '+', '-', '*', '/', and '%' for basic arithmetic, '==', '!=', '<', '>', '<=', '>=' for comparisons,fun(argument1, argument2)for function calls, and so on.
Getting back to our centimeters-to-inches program, there are two noteworthy details about the call towriteln. One is, it's invoked with five arguments (as opposed to one in the program that opened the hailing frequencies). Much like the I/O facilities found in Pascal (writeln), C (printf), or C++ (cout), D'swritelnfunction accepts a variable number of arguments (it is a "variadic function"). In D, however, users can define their own variadic functions (unlike in Pascal) that are always typesafe (unlike in C) without needing to gratuitously hijack operators (unlike in C++). The other detail is that our call towritelnawkwardly mixes formatting information with the data being formatted. Separating data from presentation is often desirable, so let's use the formatted write functionwriteflninstead:
writefln("%s'%s''\t%s", feet, inches, (feet * inchperfoot + inches) * cmperinch);
The newly-arranged call produces exactly the same output, with the difference thatwritefln's first argument describes the format entirely. '%' introduces a format specifier similar to C'sprintf, for example '%i' for integers, '%f' for floating point numbers, and '%s' for strings.
If you've usedprintf, you'd feel right at home, were it not for an odd detail: we're printingints anddoubles here—how come they are both described with the '%s' specifier, which traditionally describes only strings? The answer is simple. D's variadic argument facility giveswriteflnaccess to the actual argument types passed, setup that has two nice consequences: (1) the meaning of '%s' could be expanded to "whatever the argument's default string representation is," and (2) if you don't match the format specifier with the actual argument types, you get a clean-cut error instead of the weird behavior specific to misformattedprintfcalls (to say nothing about the security exploits made possible byprintfcalls with untrusted format strings).