Immutability and arrays

Stanislav Blinov stanislav.blinov at gmail.com
Tue Dec 14 12:13:23 UTC 2021


On Tuesday, 14 December 2021 at 08:44:02 UTC, rumbu wrote:
> I am trying to understand why in this two different cases 
> (Simple and Complex), the compiler behaviour is different.
>
> ```d
> struct SimpleStruct { int x;}
> struct ComplexStruct { int[] x; }
>
> void main()
> {
>     SimpleStruct[] buf1;
>     immutable(SimpleStruct)[] ibuf1;
>     buf1[0 .. 10] = ibuf1[0 .. 10];
>     //this works
>
>     ComplexStruct[] buf2;
>     immutable(ComplexStruct)[] ibuf2;
>
>     buf2[0 .. 10] = ibuf2[0 .. 10];
>     //error cannot implicitly convert expression `ibuf2[0..10]` 
> of type `immutable(ComplexStruct)[]` to `ComplexStruct[]`
> }
> ```

Because is(typeof(immutable(ComplexStruct).x) == 
immutable(int[])). Can't bind an array of immutable to array of 
mutable. This would require a deep copy, i.e. copy constructor.


More information about the Digitalmars-d-learn mailing list