D (The Programming Language)/d2/Modules

=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  module contains functions like. The module  is written in a file called stdio.d at. It contains code that is useful for console input and output and file input and output. It is within a package called, which also contains modules such as   or  , 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:

A Deeper Look at Imports
All D code is inside modules. In D programs, there has to be one module with a  function. If one module imports another module, the imported module's definitions becomes available to the first module. In the introductory code, the  module imported two other modules:   and. However, when  was imported, only one function was imported: the sayBye function. The syntax for that is.

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  module, there is this line: That line specifies the name of the module and the package it is located in. 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  in the definition of   in , you see the modifier. That means that the  function cannot be imported. You wouldn't be able to do, either. If you see a line that says, everything below that line is. Likewise, if you see, 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  modifier, which is the opposite of the   modifier.  Declarations marked by neither   nor   are   by default.
 * All D source files are modules, even if there is no module declaration in the file.