auto arr = [1, 2, 3] should be a static array, not a GC allocated array

Nick Treleaven nick at geany.org
Sun Jul 17 16:33:29 UTC 2022


On Sunday, 17 July 2022 at 15:23:45 UTC, Steven Schveighoffer 
wrote:
> The second statement is much better, but you need the first to 
> infer the length. Just specifying "infer the length" with a 
> `[$]` on the type is a perfect fit.

There may be ambiguity with `$` for length inside an index/slice 
expression when an inferred static array type is part of an 
expression:
https://forum.dlang.org/post/qsjahatdiyxwojcwyedm@forum.dlang.org

> You also have an issue with const conversion that's not as easy 
> to specify. e.g.:
>
> ```d
> char[74] foo = "this is a long string that I don't want to have 
> to count the characters in";
> ```

Presumably length inference would not include the terminating nul 
byte of the string literal?

> Can't use staticArray here because the type will be 
> `immutable(char)[74]`.
>
> If I want to specify it should be char, I can't do 
> `staticArray!char`, because then it doesn't infer anything.

Could add an overload for that:
https://forum.dlang.org/post/urzdeerfcvardyztxfab@forum.dlang.org

> This is a simple quality-of-life improvement. I think the 
> original PR was reverted because it allowed too much inference, 
> like:
>
> `auto[$] foo = [1,2,3,4];`
>
> I think just specifying the length is dependent on the length 
> of the literal is enough benefit to justify the change. We 
> don't need full inference of any static array type.

Threads like these always use basic element types like int or 
char. In practice the element type can be quite complex. It's a 
pain to have to write out a complex type - e.g. `typeof(x.map!(a 
=> someExpr).front)`. That could be solved by having specific 
syntax for static array literals:

```d
auto sa = $[1,2,3,4];
```

That avoids supporting partial `auto` declarations (a reason why 
Walter didn't like that PR). It also allows inference when 
passing a literal to a template function argument where the 
parameter is not already a static array. The `$[]` syntax would 
literally mean "length array", i.e. fixed length array. (Why do 
we overload the word 'static' here for arrays?)

And it's prefix syntax, which would read well with your nested 
static array example:
```d
auto foo = $[$[1,2,3,4],[5,6,7,8]];
```

It doesn't help your `char[$] foo = "immutable data";` case 
though (which would need the staticArray overload or equivalent).


More information about the Digitalmars-d mailing list