I love how D redesigned the terrible C/C++ arrays. And it's awesome that array operations like element wise +, -, etc. are built into the language - it makes me want to use arrays and slices for everything. But there are still some rough edges in the design.
What do you expect to happen when you run this:
import std;
void main() {
writeln(typeid([1, 2, 3]));
}
Maybe I'm crazy, but I would expect int[3]
to be printed. But int[]
gets printed instead.
Why? What's the reason for this design?
This automatic downconversion loses potentially useful type information by default. It also means lazy code like this:
auto array = [1, 2, 3]; // Type deduced as int[], not int[3]
performs an allocation, and thus it can't be used in @nogc or -betterC. (Not to mention that it's a completely unnecessary memory allocation).
It also means that functions that take a slice parameter:
void foo(int[] bar);
Can't be called naturally in @nogc or -betterC.
foo([1, 2, 3]) // Error: Array literal may cause GC allocation.
Instead you have to do this:
int[3] bar = [1, 2, 3];
foo(bar); // Now it works with @nogc and -betterC
This obviously isn't a huge deal but it introduces a bit of friction into the @nogc workflow. It also makes slower, allocating code easier to write by default in non @nogc code.
This decision to make array literals slice types by default seems like a bad idea in all respects. It should be changed, array literals (are) should be fixed size.
But I'm still new to D, so maybe there is something that I'm missing. Any thoughts?