foreach and element type inference

Nicolas F. via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 20 11:37:08 PST 2015


Today I stumbled upon something somewhat confusing to me with 
regards to type inference and foreach loops.

As hopefully people are aware, declaring variables works like 
this:

int[] foo = [1, 2, 3, 4];

and declaring them with type inference works like this:

auto foo = [1, 2, 3, 4];

However, if we have a foreach loop, the following is the case:

foreach (int e; foo) { } // Works as expected
foreach (auto e; foo) { } // Does not work, "Error: basic type 
expected, not auto"
foreach (e; foo) { } // Works, type inference!

Somebody on #d told me that this is due to "auto" being 
essentially meaningless other than a keyword for saying "we're 
declaring a variable", and since we're always declaring a 
variable in the case of foreach, it'd be redundant.

Allowing "auto" here, as somebody pointed out, would lead to two 
styles which may be confusing as one might mistake "foreach (e" 
to be different from "foreach (auto e", and even worse, might be 
led to believe that "e" was declared earlier in the former case.

Enforcing "auto" inside foreach declarations would break old code 
for no reason other than adding a redundant keyword to make 
things more obvious to people who don't know the semantic 
workings of "foreach" (i.e. don't realise it's always a 
declaration there).

The third, and in my opinion, most pragmatic approach to clearing 
things up is to improve the compiler error message for this 
special case of somebody trying to use "auto" inside foreach. 
"Error: basic type expected, not auto" was misleading to me, 
since it almost seems like it requires a basic type 
syntactically, which it doesn't. This would also make things 
clearer without actually changing the language spec.

TL;DR: My suggestion is to have the compiler output a specific 
error message should it encounter "auto" inside a foreach 
declaration, pointing out that "auto" is neither needed nor 
allowed in this context to get type inference.

Any thoughts or opinions on this?


More information about the Digitalmars-d mailing list