I didn't know initializing a static array from a slice of unknown length was allowed until I saw:
https://dlang.org/blog/2022/06/21/dip1000-memory-safety-in-a-modern-system-programming-language-pt-1/
// allocated in static program memory
auto hello1 = "Hello world!";
// allocated on the stack, copied from hello1
immutable(char)[12] hello2 = hello1;
How does the compiler know hello1.length
at compile-time for the initialisation of the static array? It doesn't - there is a runtime check. I think it's better to require slicing of either the static array or the slice to make that clear:
int[] s = ...;
int[2] a;
a[] = s; // copy slice to slice, checking lengths match
a = s[0..2]; // copy 2 elements, no runtime check
(The last line is recognised as a slice of compile-time known length - described here:
https://dlang.org/spec/expression.html#slice_to_static_array).
For just a = s;
, the programmer may have accidentally assumed s
was a static array, or forgot to slice it to match the static array size. I think it's bug prone. It's also hard to detect if the slice normally has a matching length but in some weird runtime condition it doesn't and it throws. It's also a hidden runtime check that could hurt performance.
Note this doesn't seem to be documented in the spec yet:
[1] https://dlang.org/spec/arrays.html#assignment
[2] https://dlang.org/spec/arrays.html#array-copying
[3] https://dlang.org/spec/arrays.html#array-initialization
[1] actually has:
//s = a; // error, as a's length is not known at compile-time
I added that to the docs but it's wrong (if this feature is to stay I will make a PR to fix that line).
[2] only talks about slices. [3] doesn't mention initializing from an lvalue. AssignExpression just links to Array Copying [2] and Array Setting (for assigning a single element).
Would deprecating this break much code? Perhaps an exploratory dmd PR could be made to see if it breaks any of the tested key projects?