Unexpected range assignment behaviour
Dennis
dkorpel at gmail.com
Fri Jul 19 15:33:34 UTC 2024
On Friday, 19 July 2024 at 09:34:13 UTC, Lewis wrote:
> But the value of $ here is 3. Why do I get a RangeError at
> runtime even though the slice is the correct size (and the same
> size as the hardcoded one that works)?
The range `0 .. 3` has compile time known length, so it gets
converted to string[3]:
```D
lookup["test"] = dynArray[0 .. 3];
// becomes
lookup["test"] = cast(string[3]) dynArray[0 .. 3];
```
The key "test" doesn't exist yet, but because it's an assignment,
it gets created.
However, `0 .. $` depends on a run-time variable here, so it
doesn't convert to a static array and does slice assignment:
```D
lookup["test"] = dynArray[0 .. $];
// becomes
lookup["test"][0 .. $] = dynArray[0 .. $];
```
Now, you get a range error because "test" doesn't exist in
`lookup`, and slice assignment doesn't create a new entry.
More information about the Digitalmars-d-learn
mailing list