Immutability and arrays

WebFreak001 d.forum at webfreak.org
Tue Dec 14 12:12:42 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[]`
> }
> ```

there are special cases in the compiler for values that have no 
mutable indirections: 
https://dlang.org/spec/const3.html#implicit_qualifier_conversions

> Values that have no mutable indirections (including structs 
> that don't contain any field with mutable indirections) can be 
> implicitly converted across mutable, const, immutable, const 
> shared, inout and inout shared.

so that first struct may be implicitly converted between 
mutable/immutable/const because it doesn't contain any mutable 
indirections (mutable arrays/pointers/references)


More information about the Digitalmars-d-learn mailing list