digitalmars.D.learn - Surprise with array idup method
- Philip Daniels (8/8) Aug 23 2012 auto x = [1,2,3];
- Jonathan M Davis (9/20) Aug 23 2012 It's the same thing that slicing does. The result is tail-const. And sin...
- Philip Daniels (4/29) Aug 23 2012 Thanks for the explanation Jonathan. Another thing to add to me
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
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
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:Thanks for the explanation Jonathan. Another thing to add to me cheat sheet of D-isms :-)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