Unexpected range assignment behaviour

Lance Bachmeier no at spam.net
Fri Jul 19 15:54:39 UTC 2024


On Friday, 19 July 2024 at 09:34:13 UTC, Lewis wrote:
> ```
> string[3][string] lookup;
> string[] dynArray = ["d", "e", "f"];
> lookup["test"] = dynArray[0..$];
> ```
>
> This fails at runtime with RangeError. But if I change that 
> last line to:
>
> ```
> lookup["test"] = dynArray[0..3];
> ```
>
> then it works. 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)? I would 
> have expected to only get a RangeError if at runtime the value 
> turned out to be wrong.

The simplest solution is to keep them consistent:

```
string[3][string] lookup;
string[3] dynArray = ["d", "e", "f"];
```

or

```
string[][string] lookup;
string[] dynArray = ["d", "e", "f"];
```

Avoid the temptation to mix static and dynamic arrays and your 
life will be easier. If you run into a situation where it's tough 
to avoid, use an explicit conversion:

```
lookup["test"] = dynArray.to!(string[3])[0..$];
```

(I don't know all the complicated under the hood stuff as others 
do, but I know what works and why.)


More information about the Digitalmars-d-learn mailing list