yeomandev
yeomandev

Reputation: 11796

How to use public imports in D

I am trying to replicate a namespace kind of pattern in D. I would like to have one class per file and be able to use a single import statement to include all classes from a group of files.

in my root folder I have moduleExp.d

import foo.module;
import std.stdio;

void main()
{
    writeln("hello world");
    auto quakk = new Quakk();
    quakk.write();
}

In my foo folder I have module1.d:

module foo.module1;
import std.stdio;

class Quakk
{
    public string name = "thename";
    public void write()
    {
        writeln(this.name);
    }
}

Also in foo folder, I have module.d which I thought I could use to publicly import all my class modules into so they can be used in moduleExp.d of the root folder.

module foo.module;
public import foo.module1;

When I try to compile on Windows from the root folder with rdmd moduleExp, I get errors:

moduleExp.d(1): Error: identifier expected following package
moduleExp.d(1): Error: ';' expected
Failed: ["dmd", "-v", "-o-", "moduleExp.d", "-I."]

I'm not sure what I'm doing wrong here. if I change line 1 in module.Exp.d to import foo.module1; then everything works.

Upvotes: 1

Views: 202

Answers (1)

yaz
yaz

Reputation: 1330

module is a reserved keyword that you shouldn't use as a module name. And what you are trying to do exists as a feature in dlang called package modules. Look in http://dlang.org/module.html for documentation.

So basically, you have a module under the folder foo, its name should be package.d, where you publicly import the modules within foo and any other modules that you want. Example:

module foo; // notice the module name is used
            // for the package module and not foo.package

public import foo.module1;
public import foo.module2;
...

And now when you want to import the package, just write import foo.

Upvotes: 6

Related Questions