Immutability and arrays

Steven Schveighoffer schveiguy at gmail.com
Tue Dec 14 15:28:30 UTC 2021


On 12/14/21 3:44 AM, 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[]`
> }
> ```
> 
> 

I know there have been several answers as to what the rules are, I want 
to answer why the rules are there.

In the first case, you have a simple struct which has a single integer 
in it. When copying that struct, you have no indirections (pointers), 
which means that adjusting the mutability is allowed:

```d
immutable s = SimpleStruct(5);
SimpleStruct s2 = s; // ok, we are making a copy of everything
```

In the second case, the `int[]` contains a pointer. So if you made a 
copy of that, you cannot change the mutability of the type, because now 
it would have a mutable pointer to immutable data:

```d
immutable s = ComplexStruct([5]);
ComplexStruct s2 = s; // error, cannot implicitly convert, there is an 
indirection
```

The WHY is this: let's say the above was allowed, `s2` is mutable, which 
means `s2.x` is mutable. Now I can do:

```d
s2.x[0] = 6;
```

And all of a sudden, immutable data has changed! This cannot be allowed, 
which is why you can't copy the struct.

All the other problems you are having are deriving from this problem.

-Steve


More information about the Digitalmars-d-learn mailing list