Thread overview
Surprise with array idup method
Aug 23, 2012
Philip Daniels
Aug 23, 2012
Jonathan M Davis
Aug 23, 2012
Philip Daniels
August 23, 2012
auto x = [1,2,3];
auto y = x.idup;
y ~= 99;   // fine!
y[0] = 99; // "Error: y[0] isn't mutable"
y.clear;   // fine!


So idup is returning an "immutable(int)[]" rather than an "immutable int[]".

I find this a bit surprising. Anybody else?



August 23, 2012
On Thursday, August 23, 2012 23:55:10 Philip Daniels wrote:
> auto x = [1,2,3];
> auto y = x.idup;
> y ~= 99; // fine!
> y[0] = 99; // "Error: y[0] isn't mutable"
> y.clear; // fine!
> 
> 
> So idup is returning an "immutable(int)[]" rather than an
> "immutable int[]".
> 
> I find this a bit surprising. Anybody else?

It's the same thing that slicing does. The result is tail-const. And since you can assign it to immutable int[] if you want to, it's more flexible this way. It just means that auto gives you a mutable array with immutable elements rather than an immutable array. And if you don't want to care what the type is but still want it to be full immutable, then just use immutable rather than auto:

immutable y = x.idup;

- Jonathan M Davis
August 23, 2012
On Thursday, 23 August 2012 at 22:03:04 UTC, Jonathan M Davis wrote:
> On Thursday, August 23, 2012 23:55:10 Philip Daniels wrote:
>> auto x = [1,2,3];
>> auto y = x.idup;
>> y ~= 99; // fine!
>> y[0] = 99; // "Error: y[0] isn't mutable"
>> y.clear; // fine!
>> 
>> 
>> So idup is returning an "immutable(int)[]" rather than an
>> "immutable int[]".
>> 
>> I find this a bit surprising. Anybody else?
>
> It's the same thing that slicing does. The result is tail-const. And since you
> can assign it to immutable int[] if you want to, it's more flexible this way.
> It just means that auto gives you a mutable array with immutable elements
> rather than an immutable array. And if you don't want to care what the type is
> but still want it to be full immutable, then just use immutable rather than
> auto:
>
> immutable y = x.idup;
>
> - Jonathan M Davis

Thanks for the explanation Jonathan. Another thing to add to me cheat sheet of D-isms :-)