# D (The Programming Language)/Printable version

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/D_(The_Programming_Language)

# Contributors
## Style Guides

* The Style Guide for the D/Phobos Lessons

## To Do List

* Finish the rest of the D (The Programming Language)/d2/.

## List of Contributors

Add yourself to this list if you have contributed to this wikibook:
* -- Jcao219 (discuss • contribs) 06:00, 22 June 2011 (UTC)

## Userbox

You may add this box to your user page.
| This user contributes to the D (The Programming Language) wikibook. | {{User:Jcao219/Userboxes/DTPLContributor}} |

# d2/Lesson 1

| Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |
| Subpages: | String Formatting - Advanced Info about std.stdio's Write Functions |

# Lesson 1: Hello, World!

In this lesson, you will learn how to use the Phobos library to write to the console. Also, you will learn some about the structure of D programs.

## Introductory Code

We will start with the absolutely necessary Hello World example.

### Hello World
## Concepts

In this lesson we see the import statement, the main function, the Phobos standard library in use, and also a code comment.

### import std.stdio

The Phobos library contains the std.stdio module which in turn contains the writeln function (along with various other functions). In order to use that function, you must first import that module. Notice that statements in D end in a semicolon.

### void main

All executable D programs contain a main function. This function does not return a value, so it is declared "void" (Technically, this is an over-simplification. Return values of main will be explained in more detail later.) This function is executed when the program runs.
Function body code is enclosed in curly brackets. Although the indentation and whitespace is only for the reader, not for the compiler, make sure you indent and format your code properly and consistently; it's generally a good coding practice.

### writeln and the write family

writeln is for writing to the standard output (console in this case). You can supply a string such as "Hello, World!" as an argument, and that string will be printed out. There are four basic flavors of this function: With or without formatting, and with or without a trailing newline. To demonstrate how they work, all of the following are equivalent (although the first and thirds ones don't flush stdout on Windows):

### /* I am a comment */

The first few lines of this program are comments. They are ignored by the compiler. Block comments are enclosed in /* */. Line comments continue after // .
This is an example of a line comment:
D also supports nested block comments, enclosed in /+ +/:
This is different from ordinary block comments which behave just like in C:

## Tips

* writeln is different from write because it adds a newline to the end.

# d2/Lesson 2

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |

# Lesson 2: Types and Declarations

In this lesson, you will learn how to declare and use variables.

## Concepts

In this lesson we see the declaration and assignment of variables.

### Declaration Syntax

The syntax of declaring variables is type identifier; You can also assign a value at the same time. type identifier = value;

### Declaring Multiple Variables in the Same Line

D allows you to declare multiple variables of the same type in the same line. If you write:
i, j, and k are all declared as ints but only k is assigned 30. It is the same as:

### Implicit Type Inference

If the declaration starts with auto, then the compiler will automatically infer the type of the declared variable. In fact, it doesn't have to be auto. Any storage class would work. Storage classes are built-in D constructs such as auto or immutable. This code declares an unchangeable variable a with a value of 3. The compiler figures out that the type is int.
You will learn much more about storage classes later.

### More about writeln

writeln is a very useful function for writing to stdout. One thing is special about writeln: it can take variables of any type. It can also take an unlimited amount of arguments. For example:
Don't worry, there is nothing magical about writeln. All the functions in the write family are implemented (in 100% valid D code) in stdio.d, which is in the Phobos standard library.

## Tips

* Syntax like this: int i, j, k = 1, 2, 3; is not allowed.
* Syntax like this: int, string i, k; is also not allowed.
* auto is not a type. You cannot do this: auto i; because there's no way the compiler can infer the type of i. auto is merely a storage class, which tells the compiler to infer the type from the value that you assign it to in that same line.

# d2/Lesson 3

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |

# Lesson 3: Intro to Functions

In this lesson, you see more of functions, which were used back in Lesson 1. If you are already familiar with another C-like language, you only need to skim this over.

## Concepts
### Functions

Functions allow you to write more organized code. With functions, you can write some code once, and then call it whenever you need to use that code.

### Function Syntax

Let's take a look at the syntax:

# d2/Lesson 4

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |
| | Subpages: | Notes for Beginners |

# Lesson 4: Types, Continued

In this lesson, you will see all the other types. Many of these types will be familiar, but be aware that there are many differences between C and D in their built-in types.

## Concepts
### Assertion

Using assert allows you to check if a certain expression is true or not. == means is equal to (do not confuse this with =, which is for assigning variables). The checking is done at runtime, and if whatever is inside the parentheses evaluates to false, then an Assertion Error will happen and the program will terminate.

### Properties and Default Initializers

Types have default initializers. That means, if they are declared but not assigned any value, they will be equal to something by default.
Properties can be queried from any type or object. When a property of a type or object is queried, a dot goes between the property name and the identifier.
The init property of any type contains the value that objects of such a type are initialized to by default. For numeral types, you can find the min and max values with their respective properties: type.min and type.max. You can also find the size of a type in memory: type.sizeof. If you want to declare but don't want to initialize something, you can do this:
Then, i is uninitialized; its value is undefined garbage.

### A Bit of D's Lexical Grammar

D allows you to write numbers in a few useful bases and forms. So, if you wanted to add the hexadecimal number of A4 to one million three hundred thirteen thousand six hundred thirty-seven and the binary number of 1011010101, you can write this:
Note that underscores in the middle of numbers are completely ignored. They are 100% optional and are useful for formatting long numbers.

## Tips

* You may look through this reference for more information about D's lexical grammar. Soon a lesson will be written that contains up-to-date information on the subject.

# d2/Lesson 5

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |

# Lesson 5: Type Conversion

In this lesson, you will learn how the types of variables can be implicitly and explicitly converted.

## Concepts
### Implicit Integral Conversions

An object of an integral type can be converted to another object of an integral type as long as the destination type is wider than the original type. These conversions are implicit:
bool ⇒ int byte ⇒ int ubyte ⇒ int short ⇒ int ushort ⇒ int char ⇒ int wchar ⇒ int dchar ⇒ uint

### Explicit Conversions

Casting is a way to tell the compiler to try to force an object to change type. In D, you do this by writing cast(type).

## Tips

* You cannot convert an integral value to a string (or the other way around) with a cast. There is a library function which you will learn later for that.

# d2/Lesson 6

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |

# Lesson 6: Modules

In this lesson, you will gain an understanding of D's module system. A module is a unit of code that contains definitions for variables, functions, and other D constructs that belong together. This is useful for creating reusable code. You've seen modules in every single lesson. In fact, all D source files are modules. The stdio module contains functions like writeln. The module stdio is written in a file called stdio.d at dmd/src/phobos/std/stdio.d. It contains code that is useful for console input and output and file input and output. It is within a package called std, which also contains modules such as std.algorithm or std.string, which you will learn about later. The Phobos library is just a big collection of modules that comes with a D compiler.

## Introductory Code

Compile like this: dmd main.d happy.d bye.d

## Concepts
### A Deeper Look at Imports

All D code is inside modules. In D programs, there has to be one module with a main function. If one module imports another module, the imported module's definitions becomes available to the first module. In the introductory code, the main module imported two other modules: module1 and byebye. However, when byebye was imported, only one function was imported: the sayBye function. The syntax for that is import modulename : identifier1, identifier2, identifier3;.

### Module Declarations

D source files can specify the name of the module and what package it belongs to with a module declaration, which goes at the beginning. For example, in the stdio module, there is this line:
That line specifies the name of the module (stdio) and the package it is located in (std). Each source file can only have a maximum of one module declaration. If there is none, the source file name (without the extension) becomes the module name.

### Visibility

Before the void in the definition of sad in module1, you see the modifier private. That means that the sad function cannot be imported. You wouldn't be able to do import module1 : sad, either. If you see a line that says private:, everything below that line is private. Likewise, if you see private { } , everything inside the curly brackets is private.

## Tips

* The name of the module does not have to relate to the names of the definitions within that module.
* The name of the module does not have to relate to the file name.
* There is also a public modifier, which is the opposite of the private modifier. Declarations marked by neither public nor private are public by default.
* All D source files are modules, even if there is no module declaration in the file.

# d2/Lesson 7

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |
| | Subpages: | What are Pointers? - What are Arrays? |

# Lesson 7: Pointers, Pass-By-Reference and Static Arrays

In this chapter, you will learn about how to use pointers and static arrays in D. You will also learn how to pass by reference without using pointers. The lesson text will not explain the concepts behind pointers and arrays, and it will assume that you have that knowledge from C or C++. D also has dynamic arrays and array slices, both of which will be covered in a later lesson.

## Introductory Code
### Pass By Reference

If you're a C++ programmer and you read the above thinking it's a step back from C++ references, then rejoice: while D supports pointers, it also supports better solutions for passing variables by reference to functions:
There is also special support for out parameters:
Using out, n in initializeNumber is default initialized at the beginning of the function.

### Using Static Arrays
## Concepts
### Reference and Dereference

The syntax in D is the same as C and C++. The operator & takes the reference of an object, and * dereferences.

### Pointer Types

In D, a pointer to typeA is:
and the code for declaring one is:

### Static Arrays

Static arrays have fixed lengths. You declare them like this:
You can also do this:
Arrays are indexed starting with the number zero for the first element. The compiler will catch you if you attempt to access an element with an index greater than or equal to that array's length. You access elements of an array like this:
You can also fill an array with a single value, so that all of that array's elements equal that value:

### As Function Arguments

Look at this code:
The output is [1,2,3], not [2,2,3]. Why? It's because static arrays are copied whenever they are passed as arguments to a function. The arr in the addOne function is only a copy of array1. Rewrite it like this:

# d2/Lesson 8

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |

# Lesson 8: Strings and Dynamic Arrays

In this chapter, you will learn about strings in depth. In the meantime, you will also learn about another type: the dynamic array.

## Concepts
### Dynamic Arrays
#### Dynamic Arrays versus Static Arrays

In the previous lesson, you learned about static arrays. Dynamic arrays are different from those in that they do not have a fixed length. Essentially, a dynamic array is a structure with this info:
* A pointer to the first element
* The length of the entire array
You create a dynamic array like this:
You can create a dynamic array initiated with a specific length:
You will learn more about the new keyword later. The syntax for filling an array with a single value is the same for both static and dynamic arrays:
Dynamic arrays are indexed in the same fashion as static arrays. The syntax for accessing an element at a certain index is the same:
However, since dynamic arrays don't have a length known at compile-time, the compiler can't check if the index that you are accessing is really within that length. Code like this would compile but would also cause a runtime Range Violation error:

#### Manipulation of Dynamic Arrays

Dynamic arrays can be combined with other dynamic arrays or even with static arrays using the ~ operator. Appending a new element to the array uses the same operator.
You shouldn't assign a dynamic array to a static array (my_static_arr = my_dynamic_arr;) unless if you are certain that my_dynamic_arr.length is the equal to my_static_arr.length. Otherwise, a runtime error will occur. You can always assign a static array to a dynamic array variable, though, since the dynamic array will automatically resize if the static array's length is too big.

#### Passing Dynamic Arrays to Functions

Dynamic Arrays are passed by value to functions. That means, when you pass a dynamic array to a function, the structure that contains the pointer to the first element and the length is copied and passed.
You learned in the last chapter that you can cause things to be passed by reference instead of by value by adding the ref modifier.

#### Array and Other Properties

These properties apply to both static and dynamic arrays:
| Property | Description |
| .init | For static arrays, it returns an array with each element initialized to its default value. |
| .sizeof | Returns the size of the array in memory. |
| .length | Returns the number of elements in the array. This is fixed in static arrays. |
| .ptr | Returns a pointer to the first element of the array. |
| .dup | Creates a dynamic array that is a copy of the array and returns it. |
| .idup | Similar to .dup but the copy's elements are immutable. |
| .reverse | Returns the array with its elements in reverse order. |
| .sort | Sorts in place the elements in the array and returns the result. |
There are also other properties which are common to every object or expression. Two of such properties are the .init and .sizeof properties.

### Immutable

In D, immutable is a storage-class just like auto. It converts a type to a non-modifiable type.
Note that immutable(type) means the same as immutable type to the compiler.

#### Storage-Classes and auto

When you have a storage class like immutable, you can omit auto for type inference.
The type of whatever is immutable is inferred from the compiler. This next code example is not valid because there is no way the compiler could infer the type:

#### Using immutable Variables

This is allowed and perfectly fine code:
It only sets b equal to the value of a. b does not have to be immutable. That changes if you are taking a reference:
You are allowed to cast the immutable away, but if you were to modify an immutable value using that hack, the result is undefined.

### Strings as Arrays

You've seen strings since Lesson 1. A string is the exact same thing as immutable(char), a dynamic array of immutable char elements. Likewise, a wstring is the same as immutable(wchar), and a dstring is the same as immutable(dchar).

#### String Properties

Strings have the same built-in properties as dynamic arrays. One useful property is the .dup property, for creating a mutable char copy of a string if you want to modify the individual characters of the string.
The .idup property is useful for creating a copy of an existing string, or for creating a string copy of a char.

#### Char Literals

A char literal is enclosed by single-quotes. There are also wchar and dchar literals.

# d2/Lesson 9

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) | |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T | Next |

# Lesson 9: Slicing and a Deeper Look into Dynamic Arrays

Slicing in D is one of the language's most powerful and useful aspects. This lesson is really more of a continuation of the last lesson - you will also get a deeper look into how D's arrays work.

## Concepts
### What are Slices?

You can take slices of arrays in D with this syntax:
The element at end_index is not included in the slice. Remember that dynamic arrays are just structures with a pointer to the first element and a length value. Taking a slice of a dynamic array simply creates a new one of those pointer structures that points to the elements of that same array.

### Three Ways to Do the Same Thing

Notice that the $ is automatically replaced with the length of the array being sliced from. The following three lines are equivalent and both create slices of the entirety of an array arr.

### The .capacity Property

All dynamic arrays in D have a .capacity property. It is the maximum number of elements that can be appended to that array without having to move the array somewhere else (reallocation).

### Maximizing Efficiency by Only Reallocating When Necessary

It is good for efficiency to make sure that appending and concatenation do not cause too many reallocations because it is an expensive procedure to reallocate a dynamic array. The following code may reallocate up to 5 times:
Make sure that the array capacity is big enough at the beginning to allow for efficient non-reallocating array appends and concatenations later if performance is a concern. You can't modify the .capacity property. You are only allowed to either modify the length, or use the reserve function.

### When Passed to Functions

Remember that D's arrays are passed to functions by value. When static arrays are passed, the entire array is copied. When a dynamic array is passed, only that structure with the pointer to the underlying array and the length is copied - the underlying array is not copied.
As you can see, there are a few possibilities if you pass a dynamic array to a function that looks like this:
* First possibility: the array's capacity was large enough to accommodate the resizing, so no reallocation occurred. The original underlying array's first element was modified.
* Second possibility: the array's capacity was not large enough to accommodate the resizing, but D's memory management was able to extend the memory space without copying the entire array. The original underlying array's first element was modified.
* Third possibility: the array's capacity was not large enough to accommodate the resizing. D's memory management had to reallocate the underlying array into a completely new space in memory. The original underlying array's first element was not modified.
What if you want to make sure that the following works?
Simply change the function f so that dynamic arrays are passed by reference:

### Appending to Slices

When you take a slice of a dynamic array, and then append to that slice, whether the slice is reallocated depends on where the slice ends. If the slice ends in the middle of the data from the original array, then appending to that slice would cause a reallocation.
Lets say you took a slice of a dynamic array, and that slice ends at where the dynamic array ends. What if you appended to the dynamic array so that the slice no longer ends at where the dynamic array's data ends?
The .capacity property of a slice does indeed depend on other references to the same data.

### Assignment-To-Slices

An Assignment-To-Slice looks like this:
You are assigning b to a slice of a You have actually seen Assignment-to-Slices in the last two lessons, even before you learned about slices. Remember this?
Remember that a is shorthand for a[0 .. $] When you assign a int slice to a single int value, that int value is assigned to all the elements within that slice. An Assignment-To-Slice always causes data to be copied.
Beware! Whenever you use Assignment-To-Slice, the left and right sides' .length values must match! If not, there will be a runtime error!
You also must make sure that the left and right slices do not overlap.

### Vector Operations

Let's say you wanted to double each and every integer element of an array. Using D's vector operation syntax, you can write any of these:
Likewise, if you wanted to perform this operation: [1, 2, 3, 4] (int a) + [3, 1, 3, 1] (int b) = [4, 3, 6, 5] You would write this:
Just like for Assignment-To-Slice, you have to make sure the left and right sides of vector operations have matching lengths, and that the slices do not overlap. If you fail to follow that rule, the result is undefined (There would be neither a runtime error nor a compile-time error).

### Defining Array Properties

You can define your own array properties by writing functions in which the first argument is an array.

## Tips

* Steven Schveighoffer's article "D Slices" is an excellent resource if you want to learn more.

# d2/Lesson 10

| | Topics: | Language and Phobos - DGui (example placeholder - can be any library) |
| Previous | Lessons: | 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - T |

# Lesson 10: Conditionals and Loops

Conditionals and loops are essential for writing D programs.

## Concepts
### The if and else Statements

Using if allows you to make part of your code only execute if a certain condition is met.
In fact, if the section of code that's inside the if or else is only one line long, you can omit the curly brackets.
As a result, this is often seen:

### The Condition

The condition that goes inside of the parentheses in conditional statements such as if can be anything convertible to bool. That includes integral and floating-point types (true if nonzero, false if otherwise) and pointers (null is false, and dynamic arrays (always true).

### The while Loop

A while loop will allow you to repeat a block of code as long as a certain condition is met. There are two forms of the while loop:
and
The difference is, in the first example, if condition1 is false, do_this is never called, while in the second example it would be called once (the conditional check happens after the code is executed once).

### The foreach Loop

This loop is for iteration. Take a look at these two ways to use foreach:

### The for Loop

This type of looping is the most complex, but it is also the one that gives a lot of control. It is defined in the same way as other C-like languages:
The initialization expression is executed only once during the beginning. Then condition is checked to be true or false. If it is true, the code inside of the conditional block (inside of the brackets) is executed. After that execution, the counting expression is executed. Then, the condition is checked, and if it is true, the loop continues. For example:
You can even omit parts of what goes inside the parentheses of the for. These two are equivalent:

### break and continue

These are two statements that are used inside of loops.
The break statement breaks out of the loop. Whenever the break statement is encountered, the loop is immediately exited. This statement can go inside of while, for, foreach, and switch blocks (you will learn about those later).
The continue statement causes a loop to restart at the beginning. Let's see, through code, exactly how this works. This code example counts to 7 but skips 5.

### Switches and More

D allows absolute branching with labels and goto.
Do not use these unless if you have to. Code that uses labels can most often be written with more readable looping constructs, like for, while, and foreach.
There is something in D, C and C++ called the switch. D's switches are actually more powerful than C and C++'s switches.
Note that you must have a break in order to get out of the switch. Otherwise, fall-through occurs. Also, you can use goto.
Strings can be used in case. This is a feature that's not in C or C++.

### else

(It doesn't seems to work in recent compilers). You can use else for foreach, while, and for loops, too. If any of those loops have an else clause, then the else is only executed if the loop terminates normally (i.e. not with break).