Search code examples
namespacesdconflict

how to resolve "conflicts with" errors in d?


I'm trying to compile some D. The code that I've written uses the std.string library as well as std.algorithm. One of my functions calls indexOf on a string: unfortunately, apparently there's also a indexOf function in std.algorithm, and the compiler doesn't like it:

assembler.d(81): Error: std.algorithm.indexOf!("a == b", string, immutable(char)).indexOf at /usr/share/dmd/src/phobos/std/algorithm.d(4431) conflicts with std.string.indexOf!(char).indexOf at /usr/share/dmd/src/phobos/std/string.d(334)
assembler.d(81): Deprecation: function std.algorithm.indexOf!("a == b", string, immutable(char)).indexOf is deprecated

How do I get around this? In C++ I could use the :: to explicitly say what namespace I'm in... what about D?


Solution

  • If you want to call std.string.indexOf explicitly, then do std.string.indexOf(str, c) instead of indexOf(str, c) or str.indexOf(c).

    Or you can use an alias:

    alias std.string.indexOf indexOf;
    

    If you put that inside the function where you're calling indexOf, then it should then consider indexOf to be std.string.indexOf for the rest of the function. Or if you put it at the module level, then it'll affect the whole module.

    However, due to a bug, UFCS (Universal Function Call Syntax) doesn't currently work with local aliases, so if you put the alias within the function, you'll have to do indexOf(str, c) instead of str.indexOf(c).

    A third option is to use a selective import:

    import std.string : indexOf;
    

    With that import, only indexOf is imported from std.string, and when you use indexOf, it'll use the string version (even if you've also import std.algorithm). And you can even import std.string regularly in addition to the selective import to get the rest of std.string, and the selective import will still fix the conflict (in which case, it's really not that different from importing std.string and then aliases indexOf). However, due to a bug, selective imports are always treated as public, so doing a selective import of indexOf in a module will affect every module that imports it (potentially causing new conflicts), so you may want to avoid it at this point.