Skip to content

Instantly share code, notes, and snippets.

@nikibobi
Last active March 5, 2019 16:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikibobi/6156492 to your computer and use it in GitHub Desktop.
Save nikibobi/6156492 to your computer and use it in GitHub Desktop.
D module import tips

Module imports

When declaring imports follow the following convention:

  1. Specify the module name module fancymodule.functions;
  2. Import all std modules import std.stdio;
  3. Import all external library modules import dsfml.system;
  4. Import all modules part of your project import fancymodule.actions;
  • Have a module named all that only publicly imports all of your library's modules:

      module fancymodule.all;
      public {
          import fancymodule.functions;
          import fancymodule.actions;
      }
    
    • Others prefer to name that module the same name as the library module fancymodule.fancymodule;
    • And others name it d module fancymodule.d;
  • Use scoped imports if you want to use only one or two functions from a module only in one 'scoped' place(in a function body etc.) in your module:

      void fun() {
          import std.stdio;
          writeln("fancy!");
      }
    
  • Use version(unittest) imports to import modules that are used only in your unittests:

      version(unittest)
      {
              import std.exception;
      }
    
  • Use selective imports when you use only one or two members from a module import std.stdio : write, writeln;

  • Use static imports when some of the module members have name conflicts with your module members or can be easily confused with some of your module logic:

      static import std.math; //or renamed: static import math = std.math;
      //some scope {
      auto sin = std.math.sin(std.math.PI); //will be confusing to have: auto sin = sin(PI);
      //}
    
  • For the above cases if you prefer to instead use renamed selective imports:

      import math = std.math : sine = sin;
      //some scope {
      auto sin = sine(math.PI);
      //}
    

Since PI is not in the selective import list of math so it has to be explicitly accessed. You can think of selective imports as static imports that allow some members not to be specified explicitly(?not sure)

  • If you have a name conflict, then use static imports(or renamed module-only static imports if the module name is too long) instead of renamed imports. So that others who read your code don't get confused for the new name:

      static import io = std.stdio; //instead of: import std.stdio : puts = writeln
      void writeln(T...)(T args) {
          io.write(args);
          io.writeln("fancy endline");
      }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment