Is [ 0, 1, 2 ] an immutable array?
Lars T. Kyllingstad
public at kyllingen.NOSPAMnet
Wed Aug 12 00:51:32 PDT 2009
Ali Cehreli wrote:
> Does the expression [ 0, 1, 2 ] form an immutable array? If so, is the assignment to a[0] undefined below? Is it trying to modify an immutable element?
>
> int[] a = [ 0, 1, 2 ];
> a[0] = 42;
>
> The reason for my thinking that [ 0, 1, 2] is an array is because it has the .dup property and this works too:
>
> int[] a = [ 0, 1, 2 ].dup;
>
> Thank you,
> Ali
>
Nope, it's an ordinary, mutable array. :) To create an immutable array
you can do like this:
// This is an immutable array of ints:
immutable int[] a = [ 0, 1, 2 ];
// This is an array of immutable ints:
immutable(int)[] a = [ 0, 1, 2 ];
The .dup property simply creates a copy of the array, which can be
useful whether the array is immutable or not.
(Note that there will be some changes in array syntax/semantics from the
next version of DMD2. In particular, arrays of type T[] will be
unresizable. Resizable arrays will have a new type, denoted T[new].)
-Lars
More information about the Digitalmars-d-learn
mailing list