Immutability and arrays
rumbu
rumbu at rumbu.ro
Tue Dec 14 13:06:45 UTC 2021
On Tuesday, 14 December 2021 at 12:13:23 UTC, Stanislav Blinov
wrote:
>
> 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.
This means that the only way to write a generic function which
copies an array of immutable elements to another array is this:
```d
void copy10(T)(T[] dst, immutable(T)[] src)
{
static if (is(immutable(T): T))
dst[0..10] = src[0..10];
else
dst[0..10] = cast(T[])src[0..10]; // or better a deep
copy
}
```
Btw, tried to give ComplexStruct a some copy constructors
(casting away immutable is just for the example, I know it's not
the way to do it).
```d
struct ComplexStruct
{
int[] x;
this(ref return scope ComplexStruct another)
{
this.x = another.x;
}
this(ref return scope immutable(ComplexStruct) another)
{
this.x = cast(int[])(another.x);
}
}
```
Still slice assignment does not work. I think I will drop
immutability, it's too complicated to work with.
More information about the Digitalmars-d-learn
mailing list