Movatterモバイル変換


[0]ホーム

URL:


DLang LogoDLang Tour
Menu

Slices

Slices are objects from typeT[] for any given typeT.Slices provide a view on a subset of an arrayofT values - or just point to the whole array.Slices and dynamic arrays are the same.

A slice consists of two members - a pointer to the starting element and thelength of the slice:

T* ptr;size_t length; // unsigned 32 bit on 32bit, unsigned 64 bit on 64bit

Getting a slice via new allocation

If a new dynamic array is created, a slice to this freshlyallocated memory is returned:

auto arr = new int[5];assert(arr.length == 5); // memory referenced in arr.ptr

Actual allocated memory in this case is completely managed by the garbagecollector. The returned slice acts as a "view" on underlying elements.

Getting a slice to existing memory

Using a slicing operator one can also get a slice pointing to some alreadyexisting memory. The slicing operator can be applied to another slice, staticarrays, structs/classes implementingopSlice and a few other entities.

In an example expressionorigin[start .. end] the slicing operator is used to geta slice of all elements oforigin fromstart to the elementbeforeend:

auto newArr = arr[1 .. 4]; // index 4 is NOT includedassert(newArr.length == 3);newArr[0] = 10; // changes newArr[0] aka arr[1]

Such slices generate a new view on existing memory. Theydon't createa new copy. If no slice holds a reference to that memory anymore - or aslicedpart of it - it will be freed by the garbage collector.

Using slices, it's possible to write very efficient code for things (like parsers, for example)that only operate on one memory block, and slice only the parts they really needto work on. In this way, there's no need to allocate new memory blocks.

As seen in theprevious section, the[$] expression is a shorthand form forarr.length. Hencearr[$] indexes the element one past the slice's end, andthus would generate aRangeError (if bounds-checking hasn't been disabled).

In-depth

rdmd playground.d


[8]ページ先頭

©2009-2025 Movatter.jp