On Sunday, February 25, 2018 05:24:54 psychoticRabbit via Digitalmars-d- learn wrote: > Hi. Anyone know whether something like this is possible? > > I've tried various conversions/casts, but no luck yet. > > Essentially, I want to cast the result set of the iota to an > array, during initialisation of the variable. > > no, I don't want to use 'auto'. I want an array object ;-) > > -------------- > module test; > > import std.stdio; > import std.range : iota; > > void main() > { > int[] intArr = iota(1, 11); // 1..10 > double[] doubleArr = iota(1.0, 11.0); // 1.0..10.0 > char[] charArr = iota('a', '{'); // a..z > } > -------------
As with any range, you can call std.array.array to convert it to an array. So, you can have: int[] intArr = iota(1, 11).array(); or more idiomatically: auto intArr = iota(1, 11).array(); And auto does _not_ mean that it's not an array. It just means that the type is inferred, which is pretty much required when you're dealing with ranges, because the range types get a bit disgusting to type even if they're not Voldemort types, and if they are Voldemort types, then you pretty much have to use auto, since you can't refer to the type by name. But in general, even when you know exactly what the type is, it's good practice to use auto, since then you're avoiding repeating the type, and it makes it so that you don't have to change as much code later if the type of the variable changes. The classic example of where auto should be used when you know exactly what the type is would be with new. e.g. MyClass c = new MyClass; is unnecessarily redundant, and auto c = new MyClass; is preferred. In your case, providing the type isn't redundant, since the type isn't listed on the right-hand side of the expression, but it's still unnecessary to list the type, so auto is generally preferred - though obviously, if you really want to be explicit about the types everywhere, there's nothing stopping you from doing so. It just makes the code harder to maintain if the type ever changes. - Jonathan M Davis