Importing Modules

Learn how to import different modules.

The import keyword, which we have used in almost every program so far, is for introducing a new module to the current module:

import std.stdio;

The module name may contain the package name as well. For example, the std. part above indicates that stdio is a module that is a part of the std package.

The animal.cat and animal.dog modules would be imported similarly. Let’s assume that the following code is inside a file named “deneme.d”:

module deneme; // the name of this module

import animal.cat; // a module that it uses
import animal.dog; // another module that it uses

void main() {
    auto cat = new Cat();
    auto dog = new Dog(); 
}

Note: As described below, for the program to be built correctly, those module files must also be provided to the linker.

More than one module can be imported at the same time:

import animal.cat, animal.dog;

Selective imports

Instead of importing a module as a whole with all of its names, it is possible to import just specific names from it.

Press + to interact
import std.stdio : writeln;
void main() {
writefln("Hello %s.", name); // ← compilation ERROR
}

The code above cannot be compiled because only writeln is imported, not writefln. Selective imports are considered to be better than importing an entire module because they reduce the chance of name collisions. As you will see in an example below, a name collision can occur when the same name appears in more than one imported module.

Selective imports may reduce compilation times as well because the compiler needs to compile only the parts of a module that are actually imported. On the other hand, selective imports require more work since every imported name must be specified separately on the import line.

This course does not take advantage of selective imports mostly for brevity.

Local imports

So far, we have always imported ...