C-like static array size inference - how?
Ali Çehreli
acehreli at yahoo.com
Tue Jun 7 00:20:31 UTC 2022
On 6/6/22 17:04, arandomonlooker wrote:
> I usually transcribe them as follows, because the previous syntax causes
> a compiler error:
>
> ```d
> int numbersINeed[] = [1, 2, 3, 4, 5];
> ```
As you already know, the correct syntax is 'int[]' :) but it won't work
because -betterC cannot support dynamic array.
> it's complaining about TypeInfo being absent.
What an unfortunate error message! Trying writeln() causes equally weird
error messages.
> Can't i use some feature to imply that D must deduct the size
> from the array i am assigning, like an underscore? Can't D do that?
That request comes up relatively frequently. Currently, the only way I
know of is to use std.array.staticArray:
import std.array;
extern (C)
void main() {
auto numbersINeed = staticArray([1, 2, 3, 4, 5]);
import std.range;
import std.algorithm;
import core.stdc.stdio;
// |
// V
numbersINeed[].each!(n => printf("%d ", n));
}
Aside: I printed the elements with a range algorithm, which is not
necessary at all. However, the reason I had to use it is because static
arrays are not ranges because their lengths cannot change. [] takes a
slice to all elements, which can reduce its length, and accordingly is a
range.
Ali
More information about the Digitalmars-d-learn
mailing list