Skip to content
Arrays and Slices
step 1/5

Reading — step 1 of 5

Learn

~2 min readStrings, Arrays, Templates

D's array model is unique among C-family languages: arrays are slices (pointer + length pair) over a backing storage.

Array literals

int[] a = [1, 2, 3, 4, 5];
string[] names = ["Ada", "Bob", "Carol"];
int[5] fixed = [1, 2, 3, 4, 5];   // fixed-length

// Properties
a.length    // 5
a.dup       // shallow copy
a.idup      // immutable copy

Slicing

int[] a = [10, 20, 30, 40, 50];
a[0..3]     // [10, 20, 30] — first 3
a[2..$]     // [30, 40, 50] — from index 2 to end
a[1..$-1]   // [20, 30, 40] — exclude first and last

Slices share storage — they're cheap O(1) references, not copies.

Mutation

int[] a = [1, 2, 3];
a ~= 4;             // append (may allocate)
a ~= [5, 6, 7];     // append another array
a = a[1..$];        // drop first element (shrink slice)

Multi-dim

int[3][3] matrix = [[1,2,3], [4,5,6], [7,8,9]];   // fixed
int[][] dynamic = [[1, 2], [3, 4, 5], [6]];        // jagged

Associative arrays (hash maps)

int[string] ages;
ages["Ada"] = 36;
ages["Bob"] = 25;

ages["Ada"]                  // 36
"Carol" in ages              // null (use as bool: false-ish)

foreach (name, age; ages) {
    writeln(name, ": ", age);
}

Range operations on arrays

From Fundamentals: map, filter, reduce, sort, chunk. Most arrays in D get used through these:

import std.algorithm;

int[] nums = [3, 1, 4, 1, 5, 9, 2, 6];
auto sorted = nums.dup.sort;       // .dup because sort mutates
auto evens = nums.filter!(x => x % 2 == 0).array;
auto total = nums.sum;
auto unique = nums.sort.uniq;

Memory management

Arrays are GC-managed by default. To use without GC:

  • core.stdc.stdlib for malloc/free
  • @nogc annotation
  • Phobos provides Mallocator and friends

For systems programming where GC is unwanted, D supports it — but most application code uses the default GC happily.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…