www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Surprise with array idup method

reply "Philip Daniels" <foo foo.com> writes:
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?
Aug 23 2012
parent reply "Jonathan M Davis" <jmdavisProg gmx.com> writes:
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
Aug 23 2012
parent "Philip Daniels" <foo foo.com> writes:
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 :-)
Aug 23 2012