On Friday, 4 December 2015 at 01:10:41 UTC, Jim Barnett wrote:
Really? If it leads to "hard to detect errors", I have a hard time believing that can be "idiomatic D".

It's used throughout the standard library, granted I don't think there's any occurrences of importing inside a while loop. The issues with nested imports are well known but also hard to fix without breaking code. However, they cut down on template bloat and the standard library makes very heavy use of templates. Thus a tradeoff is made. It's usually not nested imports by themselves that create these hard to detect errors, however. It's a few different D features working in concert.

Observe the following code:

struct Test
{
        int num = 1;
        string text = `"this is a line of text"`;
        
        void printMessage()
        {
                import std.conv, std.stdio;
                
                writeln(text("My text is ", text, " and my num is ", num));
        }
}

void main()
{
        Test t;
        t.printMessage();
}

It prints: "My text is  and my num is 0"

Why the empty space? Because instead of referring to this.text inside of the printMessage method, `text` refers to std.conv.text. The nested import overrides the member variable in the outer scope.

I have never seen a language that encourages the user to specify dependencies inside a loop. I am hoping I misunderstood something here.

Sorry, I thought you were referring more generally to nested imports. No, imports in a while loop are not encouraged; imports in a struct or a template are.

Reply via email to