FYI: Be careful with imports when using public:

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Oct 10 07:43:26 UTC 2023


I just thought that I'd point this out, since I got bit by it, and others
might be in the same boat, but apparently, if you have code such as

    struct Foo
    {
    public:
        import std.range.primitives;
    ...
    }

then the import is treated as public (and the same goes if you use public:
at the module level and have module-level imports under it). In this
particular case, the confusing result is that trying to call functions in
std.range.primitives (such as walkLength or moveFront) on an instance of Foo
using UFCS will result in the code not compiling (whereas using the normal
function call syntax works just fine), and the error messages don't make it
all clear as to why, so it took me quite a while to figure out what the
problem was.

In retrospect, it seems like it probably should have been obvious that using
public: would affect all imports below it in that scope, just like it does
with any of the symbols in that scope, but since I rarely do anything with
public imports, I tend to forget that they're a thing, and it had never
occurred to me that public: could affect imports (or if it had, I completely
forgot).

So, for those of you who use public: and private: (rather than marking each
symbol individually with public or private) should be careful to make sure
that no imports are under a public: unless that's what you actually want
(which you probably don't, since that's rarely desirable; usually, that sort
of thing would only be done in a package.d module).

I don't know if the issue that I had with UFCS is expected (probably), but
the larger issue is of course that you don't want to accidentally make
imports public - especially in libraries - so clearly, anyone using public:
needs to be careful with their imports (or just mark symbols with public or
private individually instead, which has its own pros and cons, but it won't
result in accidentally making imports public, so that would definitely be
one of its pros).

- Jonathan M Davis





More information about the Digitalmars-d mailing list