Search code examples
moduled

How do I prevent a function from being imported from my module?


I'm looking for something like private attribute working not with class members, but with module entities. Functions, classes, enumerators etc.

For instance, in Erlang there is an export attribute, which goes like this: -export([fun1, fun2]), meaning only fun1 and fun2 of all the functions in the module would be exported. In D everything seems to be exported by default, which is ok, but is there a way to prevent something specific from that?


Solution

  • In the module being imported, you can mark anything private to keep it from being accessible from other modules. private works the same way on module level entities as it does on class members - inaccessible outside the module, usable inside the module. However, currently it is still visible, so it can create silly errors like "private function foo from module A conflicts with function foo from module B", forcing you to disambiguate the name. (I, and several others, are hoping to get this changed at some point, since it obviously shouldn't be a problem!)

    In the module doing the importing, you can't say "import all except", but you can import a list of specific names without importing others:

    import std.stdio : File, writefln;
    
    void main() {
    File f; // cool
    writefln("hello"); // cool
    writeln("hey"); // "Error: 'writeln' is not defined" - the selective import didn't pull this name at all
    }