Why are modules explicitly named in files?
From the D language reference:
Modules have a one-to-one correspondence with source files. The module name is the file name with the path and extension stripped off.
Module names are still specified in files explicitly, 开发者_运维问答though.
module foo;
What's the point of this? If modules correspond to files, why can't the compiler infer what they're called from the file names?
same page a bit down (emph mine)
The ModuleDeclaration sets the name of the module and what package it belongs to. If absent, the module name is taken to be the same name (stripped of path and extension) of the source file name.
this means that if you want to put a module in a package you have to explicitly specify it is (like Java's package
declaration) and given the strange propensity of people to use odd/foreign directory names you can't rely on checking for source/src/import in the path
the reason that filename and module name don't have to be the same can be so you can use a .di for import and use several versions of the actual code using -c switch to create the .obj file for linking of the different versions (though fiddling with the import path is handier for that)
It can infer it. You don't have to give the module name. However, you can give the module name, which allows you to give it an entirely different name if you want to. A prime example of this is if the file name isn't a valid module name (e.g. my-module.d). In such a case, you can use the module
declaration to give it a valid module name (e.g. my_module).
It's common practice to put the module name at the top of the file, and usually the module name is the same as the file name, but making it possible to have the module name not exactly match the file name increases flexibility.
Personally, I would generally consider it a bad idea to name the module anything other than the file name, and I'd argue that if the file isn't a valid module name, then the file name should be changed so that it is one, but apparently it was decided that the extra flexibility of making it possible for them not to match was worth having. So, it's in the language.
精彩评论