On Friday, 19 July 2024 at 15:33:34 UTC, Dennis wrote:
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.

Hi Dennis, I undestood your explanation, and based on that couldn't this case for example be caught during the compiling time?

Thanks,

Matheus.

Reply via email to