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

Nick Treleaven nick at geany.org
Mon Jul 18 16:52:47 UTC 2022


On Sunday, 17 July 2022 at 20:07:37 UTC, Steven Schveighoffer 
wrote:
> On Sunday, 17 July 2022 at 16:33:29 UTC, Nick Treleaven wrote:
>> 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
>
> It would not be ambiguous, as `int[$]` would refer to the new 
> type.

OK, hopefully it is straightforward to implement that.

> I'm having a hard time believing that kind of expression is 
> currently used anywhere.

Probably not common, theoretically possible. The linked example 
doesn't compile. I expect it's OK to change.

>> Presumably length inference would not include the terminating 
>> nul byte of the string literal?
>
> Of course, that's not actually included in the literal length. 
> e.g. `"".length == 0`.

OK, I think that's the correct choice. It does mean `arr.ptr` 
isn't nul-terminated to pass to C, using length inference. That 
would mean people need to be careful doing that with a string 
literal and manually write the \0. Currently you have to think 
about the size of the array.

...
> The use case for this escapes me. You can't do this with 
> staticArray anyway.
>
> ```d
> auto x = arr.map!(a => a * 2).array.staticArray; // error, 
> can't pass Something[] to staticArray
> ```

Yes, bad example. There may be meta-programming related cases 
though, e.g.:
```d
CommonType!(mixin(someLongExpr))[$] arr = [mixin(someLongExpr)];
```
auto + fixed-length array literal would be better there. Probably 
not common though.

...
>> 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.
>
> I'm not opposed to it exactly. But it does suffer the same 
> problems as `staticArray`.

Yes, but it doesn't need an import and is concise.

> It is sometimes nice to use the left-hand-side of the 
> construction/assignment to determine how the literal is 
> interpreted.

Yes. And if a literal is needed, one could use `cast(T[$])` 
(assuming T is simple).



More information about the Digitalmars-d mailing list