var.opSlice

var opSlice(size_t start, size_t end) const @safe

Slice an array to create a new var containing a subrange of elements.

This enables D's slice syntax: v[start .. end], v[1 .. $], v[0 .. $ - 1], etc.

Preconditions:

  • The current value must be Type.ARRAY or Type.NULL.
  • start <= end and end <= length, otherwise an assertion fails.

    Parameters

    startThe starting index (inclusive).
    endThe ending index (exclusive).

    Returns

    A new var of type Type.ARRAY containing the sliced elements. For Type.NULL, returns an empty array if start == end == 0.

    Examples

    var a = var([1, 2, 3, 4, 5]);
    var slice = a[1 .. 4];  // [2, 3, 4]
    assert(slice.length == 3);
    assert(slice[0].as!int == 2);
    
    var last2 = a[$ - 2 .. $];  // [4, 5]
    assert(last2.length == 2);