[Article Contest, first draft] D Slices

Andrej Mitrovic andrej.mitrovich at gmail.com
Wed May 18 13:22:50 PDT 2011


Well consider me enlightened. From all the things I've read before
this article, I thought a slice is a special feature that is only
introduced when you take an [n..m] from an array, e.g. my
understanding was something like:

int[] a = new int[5];  // a is definitely a dynamic array
auto b = a[1..3];  // take a slice and make b an array of length 2,
pointing at a[1..3];

Where "making an array" would just mean creating a new struct with a
pointer and a length, not allocating memory for the elements.

Your article should have been in TDPL. Good work!

It might be a good idea to mention how you can take a slice of a
static array to make it passable to functions which expect slices. A
lot of functions (all of them?) in Phobos expect slices and not static
arrays, but it's not at all obvious.

E.g. if you try to do this it will fail to compile with an extremely
ugly message:
    int[4] arr1 = [ 1, 2, 3, 4 ];
    auto mapped = map!("a + a")(arr1);

testmap.d(10): Error: template std.algorithm.map!("a + a").map(Range)
if (isInputRange!(Unqual!(Range))) does not match any function
template declaration
testmap.d(10): Error: template std.algorithm.map!("a + a").map(Range)
if (isInputRange!(Unqual!(Range))) cannot deduce template function
from argument types !()(int[4u])

All that has to be done is to take a slice:
    int[4] arr1 = [ 1, 2, 3, 4 ];
    auto mapped = map!("a + a")(arr1[]);

Come to think of it, these types of errors could be caught by the
compiler to output a nicer error message, imo.


More information about the Digitalmars-d mailing list