how is this array subtyping inside struct (bug?) possible?
mw
mingwu at gmail.com
Mon Aug 10 02:50:20 UTC 2020
On Monday, 10 August 2020 at 02:38:55 UTC, RazvanN wrote:
> On Sunday, 9 August 2020 at 21:12:58 UTC, mw wrote:
>
>> I'm *directly* access the underlying array, so why its length
>> changed to 0 after writeln?
>>
> You are accessing the underlying array after it was consumed.
> The line writeln(s0.fns) passes class, if you want to pass the
> underlying array you should type `writeln(so.fns.array)` and
> then it will not consume the array.
I know that; and that's exactly I call it a subtyping bug: i.e.
directly access & access via subtyping behave differently:
```
foreach (i; 0..3) {
S* s1 = new S();
*s1 = s0; // copy the value from s0 to *s1
writeln(s0.fns.array);
writeln(s0.fns.array.length); //*directly* access the
underlying array
}
```
output:
```
["abc"]
1
["abc"]
1
["abc"]
1
```
via subtyping:
```
foreach (i; 0..3) {
S* s1 = new S();
*s1 = s0; // copy the value from s0 to *s1
writeln(s0.fns);
writeln(s0.fns.length);
}
```
output:
```
["abc"]
0
[]
0
[]
0
```
And the direct access is the expected behavior that the subtyping
mechanism want to provide a convenience for.
Since it introduce a surprise to the user, I'd call that a bug.
>> So a plain array *is* also a range? I've thought (an array's)
>> range is a *separate* struct (which wrap the original array).
>> The wrapper range can be consumed, but the underlying array
>> should stay the same.
>>
>> I never seen it's mentioned in the doc:
>>
>> https://dlang.org/spec/arrays.html
>
> You had a type in your code.
What do you mean? can you elaborate?
More information about the Digitalmars-d
mailing list