Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Learning D
Learning D

Learning D: Leverage the modern convenience and modelling power of the D programming language to develop software with native efficiency

Arrow left icon
Profile Icon Michael Parker
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (3 Ratings)
Paperback Nov 2015 464 pages 1st Edition
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Michael Parker
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7 (3 Ratings)
Paperback Nov 2015 464 pages 1st Edition
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning D

Chapter 2. Building a Foundation with D Fundamentals

In this chapter and the next, we're going to look at the fundamental building blocks of D programming. There's a lot of information to cover, so our focus in both chapters will primarily be on the syntax, differences from other C-family languages, and how to avoid common beginner mistakes.

If you enter the code snippets into a text editor and try to compile them as you work through this chapter and the rest of the book, please keep the following in mind. Many of the snippets make use of one or more functions from std.stdio. In order to be successfully compiled, they all require a main function. However, both declarations are often missing from the snippets listed in the book in the interest of saving space. Use the following as a template to implement any such snippets yourself:

import std.stdio;
void main() {
    // Insert snippet here
}

Here's how this chapter is going to play out:

  • The very basics: Identifiers,...

The very basics

With the exception of source code comments, everything in this section is required knowledge for anyone who intends to successfully compile a D program.

Identifiers

The names of variables, functions, user-defined types, and so on, are all identifiers. Identifiers are case-sensitive and can consist of any combination and number of Universal Character Names (UCN), underscores, and digits. D does not itself define what constitutes a valid UCN. Instead, it refers to the list of valid UCNs specified in Annex D of the C99 standard. Aside from the English alphabet, characters from several languages are valid UCNs. Henceforth, I will refer to UCNs as letters. Identifiers in this book will be constrained to the English alphabet.

There are a few rules to follow when choosing identifiers:

  • The first character in an identifier can only be a letter or an underscore.
  • The use of two leading underscores is reserved for the compiler implementation. This is currently not enforced by the compiler...

Basic types

Most of D's basic data types will be familiar to C-family programmers. In this section, we're first going to look at what the basic data types are. Then we'll discuss a couple of features that are related not only to the basic types, but to all types.

The types

First up, D includes the special type void to mean no type. There is no such thing as a variable of type void. As in C, void is used to indicate that a function does not return a value. void pointers can be declared to represent pointers to any type.

Instances of the bool type are guaranteed to be eight bits in size and can hold one of two possible values: true and false. In any expression that expects a Boolean value, any zero value is converted to false and non-zero is converted to true. Conversely, in any expression that expects a numeric type, false and true are converted to 0 and 1. Variables of type bool are initialized to false by default.

D supports signed and unsigned versions of integral types in...

Basic operators

This section is a whirlwind tour of the basic operators D supports. For the most part, things are the same as they are in C. There are a few minor differences that will be highlighted as we come to them. More operators will appear later in this chapter and throughout the book. You can read more about D's operators at http://dlang.org/expression.html.

Arithmetic operators

All of the common arithmetic operators are available: +, -, *, / and %, representing addition, subtraction, multiplication, division, and modulus respectively. Additionally, D has an exponentiation operator, ^^, which raises the left operand to an exponent (power) represented by the right operand. For example, 22 can be expressed as 2 ^^ 2.

D also supports the standard increment and decrement operators. In the prefix form (++x and --x), the result of the expression is the new value. In the postfix form (x++ and x--), the result is the original value of the operand. To be more explicit, under the hood...

Derived data types

In this section, we're going to observe D's take on pointers, arrays, strings, and associative arrays. Much of what we'll cover here is very different from other C-family languages.

Pointers

As in other languages that support them, pointers in D are special variables intended to hold memory addresses. Take a moment to compile and run the following:

int* p;
writeln("p's value is ", p);
writeln("p's type is ", typeid(p));
writeln("p's size is ", p.sizeof);	

First, look at the declaration. It should look very familiar to many C-family programmers. All pointer declarations are default initialized to null, so here the first call to writeln prints "null" as the value. The type of p printed in the second writeln is int*. The last line will print 4 in 32-bit and 8 in 64-bit.

So far so good. Now look at the following line and guess what type b is:

int* a, b;

No, b is not an int, it is an int*. The equivalent C or C...

Control flow statements

D includes the traditional loop and conditional statements found in other C-family languages. It also supports the infamous goto statement. It has a couple of other useful statements, such as a built-in foreach statement and a rather unique scope statement. In this section, we're going to look at examples of each of the first two. Because of their relation with exceptions, scope statements are included in detail in the next chapter.

Traditional loops

In terms of looping constructs, we have for, do, and do-while. The syntax and behavior should be familiar. Here is an example of each iterating over an array:

auto items = [10,20,30,40,50];
for(int i=0; i<items.length; ++i)
  writeln(items[i]);

int i = 0;
while(i < items.length)
  writeln(items[i++]);

i = 0;
do {
  writeln(items[i++]);
} while(i < items.length);

No surprises there. The braces are optional with for and while when they only contain one statement. When a loop with an empty body is desired, the...

The very basics


With the exception of source code comments, everything in this section is required knowledge for anyone who intends to successfully compile a D program.

Identifiers

The names of variables, functions, user-defined types, and so on, are all identifiers. Identifiers are case-sensitive and can consist of any combination and number of Universal Character Names (UCN), underscores, and digits. D does not itself define what constitutes a valid UCN. Instead, it refers to the list of valid UCNs specified in Annex D of the C99 standard. Aside from the English alphabet, characters from several languages are valid UCNs. Henceforth, I will refer to UCNs as letters. Identifiers in this book will be constrained to the English alphabet.

There are a few rules to follow when choosing identifiers:

  • The first character in an identifier can only be a letter or an underscore.

  • The use of two leading underscores is reserved for the compiler implementation. This is currently not enforced by the compiler...

Basic types


Most of D's basic data types will be familiar to C-family programmers. In this section, we're first going to look at what the basic data types are. Then we'll discuss a couple of features that are related not only to the basic types, but to all types.

The types

First up, D includes the special type void to mean no type. There is no such thing as a variable of type void. As in C, void is used to indicate that a function does not return a value. void pointers can be declared to represent pointers to any type.

Instances of the bool type are guaranteed to be eight bits in size and can hold one of two possible values: true and false. In any expression that expects a Boolean value, any zero value is converted to false and non-zero is converted to true. Conversely, in any expression that expects a numeric type, false and true are converted to 0 and 1. Variables of type bool are initialized to false by default.

D supports signed and unsigned versions of integral types in 8-, 16-, 32-, and...

Basic operators


This section is a whirlwind tour of the basic operators D supports. For the most part, things are the same as they are in C. There are a few minor differences that will be highlighted as we come to them. More operators will appear later in this chapter and throughout the book. You can read more about D's operators at http://dlang.org/expression.html.

Arithmetic operators

All of the common arithmetic operators are available: +, -, *, / and %, representing addition, subtraction, multiplication, division, and modulus respectively. Additionally, D has an exponentiation operator, ^^, which raises the left operand to an exponent (power) represented by the right operand. For example, 22 can be expressed as 2 ^^ 2.

D also supports the standard increment and decrement operators. In the prefix form (++x and --x), the result of the expression is the new value. In the postfix form (x++ and x--), the result is the original value of the operand. To be more explicit, under the hood D is...

Derived data types


In this section, we're going to observe D's take on pointers, arrays, strings, and associative arrays. Much of what we'll cover here is very different from other C-family languages.

Pointers

As in other languages that support them, pointers in D are special variables intended to hold memory addresses. Take a moment to compile and run the following:

int* p;
writeln("p's value is ", p);
writeln("p's type is ", typeid(p));
writeln("p's size is ", p.sizeof);	

First, look at the declaration. It should look very familiar to many C-family programmers. All pointer declarations are default initialized to null, so here the first call to writeln prints "null" as the value. The type of p printed in the second writeln is int*. The last line will print 4 in 32-bit and 8 in 64-bit.

So far so good. Now look at the following line and guess what type b is:

int* a, b;

No, b is not an int, it is an int*. The equivalent C or C++ code would look like this:

int *x, *y;

In D, x would be interpreted as...

Left arrow icon Right arrow icon

Key benefits

  • Acquire the skills to understand the fundamentals of D through its support for imperative and object-oriented programming
  • Take advantage of D’s powerful compile-time features, templates and ranges to apply generative, generic, and functional style
  • A systematic guide that will help you become familiar with the concepts in D with the help of simple and easy-to-understand examples

Description

D is a modern programming language that is both powerful and efficient. It combines multiple paradigms in a way that opens up a whole new world of software design. It is used to develop both desktop and web applications, with future targets including mobile, and is available on multiple platforms. It is familiar to anyone with some experience in one or more of the C-family languages. However, hidden in the similarities are several differences that can be surprising when trying to apply common idioms from other languages. When learning D on your own, this can make it more time-consuming to master. In order to make the most of the language and become an idiomatic D programmer, it’s necessary to learn how to think in D. This book familiarizes you with D from the ground up, with a heavy focus on helping you to avoid surprises so that you can take your D knowledge to the next level more quickly and painlessly. Your journey begins with a taste of the language and the basics of compiling D programs with DMD, the reference D compiler developed by Digital Mars, and DUB, a community-developed build utility and package manager. You then set out on an exploration of major language features. This begins with the fundamentals of D, including built-in types, conditionals, loops and all of the basic building-blocks of a D program, followed by an examination of D’s object-oriented programming support. You’ll learn how these features differ from languages you may already be familiar with. Next up are D’s compile-time features, such as Compile-Time Function Evaluation and conditional compilation, then generic programming with templates. After that, you’ll learn the more advanced features of ranges and functional pipeline programming. To enhance your D experience, you are next taken on a tour of the D ecosystem and learn how to make D interact with C. Finally, you get a look at D web development using the vibe.d project and the book closes with some handy advice on where to go next.

Who is this book for?

This book is intended for those with some background in a C-family language who want to learn how to apply their knowledge and experience to D. Perhaps you’re a college student looking to use D for hobby projects, or a career programmer interested in expanding your skillset. This book will help you get up to speed with the language and avoid common pitfalls that arise when translating C-family experience to D.

What you will learn

  • Compile programs with DMD and manage projects with DUB
  • Work efficiently by binding your D programs with new and existing C libraries
  • Generate code at compile-time to enhance runtime performance
  • Implement complex templates for more powerful generic code
  • Write idiomatic D with range-based functional pipelines
  • Use the DUB repository to find a link with a variety of D libraries
  • Implement a web-app in D from the ground up

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 27, 2015
Length: 464 pages
Edition : 1st
Language : English
ISBN-13 : 9781783552481
Category :

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 27, 2015
Length: 464 pages
Edition : 1st
Language : English
ISBN-13 : 9781783552481
Category :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 113.97
D Cookbook
€41.99
Learning D
€41.99
D Web Development
€29.99
Total 113.97 Stars icon
Banner background image

Table of Contents

12 Chapters
1. How to Get a D in Programming Chevron down icon Chevron up icon
2. Building a Foundation with D Fundamentals Chevron down icon Chevron up icon
3. Programming Objects the D Way Chevron down icon Chevron up icon
4. Running Code at Compile Time Chevron down icon Chevron up icon
5. Generic Programming Made Easy Chevron down icon Chevron up icon
6. Understanding Ranges Chevron down icon Chevron up icon
7. Composing Functional Pipelines with Algorithms and Ranges Chevron down icon Chevron up icon
8. Exploring the Wide World of D Chevron down icon Chevron up icon
9. Connecting D with C Chevron down icon Chevron up icon
10. Taking D Online Chevron down icon Chevron up icon
11. Taking D to the Next Level Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.7
(3 Ratings)
5 star 66.7%
4 star 33.3%
3 star 0%
2 star 0%
1 star 0%
Daniel Kozak Jan 25, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is a really good book. Author explain things in a comprehensible way. If you are interesting in learning a D language and have some basic knowledge in any of similar languages like C++, C, Java, C#.... This book is definitely right for you. If you are already familiar with D ( or even advanced in D same as me :) ) this book will help you to extend your knowledge and clarify them.
Amazon Verified review Amazon
Lance Bachmeier Jan 28, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is an excellent resource for those with some knowledge of the D programming language (Ali Cehreli's book is a better introduction to the language). The chapters are built on examples that are easy to follow, yet provide enough detail to be of use in your own projects. The individual sections are packed with so much information that you'll want to read through them several times.The author is a gifted writer. D programmers are very lucky to have a resource like this available. It's like Knuth decided to write a book on the D programming language.
Amazon Verified review Amazon
Dylan Allbee Jan 25, 2016
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
What I love about Michael Parker's treatment of D is that he manages to give an overview which is both comprehensive and understandable. His examples contain only the relevant portions, keeping the focus away from implementation boilerplate. Parker also does a very good job of pointing out potential mistakes to avoid and provides tips for coding idiomaticallyThere are several sections of the book (mostly in the "Taking D to the Next Level" chapter) which should have either received more attention, or simply have been left out.I'd recommend reading this for anyone interested in D with at least some background in programming.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.