Note: This website is archived. For up-to-date information about D projects and development, please visit wiki.dlang.org.

Changes between Version 37 and Version 38 of ArrayArticle

Show
Ignore:
Author:
schveiguy (IP: 72.70.59.98)
Timestamp:
05/31/11 12:30:47 (13 years ago)
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ArrayArticle

    v37 v38  
    2424== Introducing Slices == 
    2525 
    26 So how does D improve things?  In many ways, D's arrays are similar to C's arrays.  In fact, D supports C's array syntax using pointers.  However, D provides a new type that builds on C array syntax called a slice.  A slice is a segment of an array (dynamic or otherwise) that tracks both the pointer ''and'' the length of the segment.  With the combined protection of having the length of the data, and the garbage collector to manage the memory backing the data, slices are an extremely powerful, dynamic concept that is safe from most memory corruption issues.  With D slices, one can write high-performance code with elegant and concise syntax that is awkward or inefficient in almost any other language. 
     26So how does D improve things?  In many ways, D's arrays are similar to C's arrays.  In fact, D supports C's array syntax using pointers.  However, D provides a new type that builds on C array syntax called a slice.  A slice is a segment of an array (dynamic or otherwise) that tracks both the pointer ''and'' the length of the segment.  With the combined protection of having the length of the data, and the garbage collector to manage the memory backing the data, slices are an extremely powerful, dynamic concept that is safe from most memory corruption issues.  In addition, D slices support extending with simple functions which take a slice as the first parameter.  This allows one to add any functionality you want to a built-in type via properties or methods. With D slices, one can write high-performance code with elegant and concise syntax that is awkward or inefficient in almost any other language. 
    2727 
    2828So let's see some D slices in action: 
    8383{ 
    8484   int[] arr = new int[5]; 
    85    shrinkTo2(arr); 
     85   arr.shrinkTo2();     // note the ability to call shrinkTo2 as a method 
    8686   writeln(arr.length); // outputs 5 
    8787}