0

Is there a way to create an immutable associative array in D? There doesn't seem to be a way to define an associative array; only declare one.

immutable char[][char[]] = ["testk" = "testv", "testk2" = "testv2"];
Jeroen
  • 15,257
  • 12
  • 59
  • 102
  • Do you really need to use char[] ? What is the point? – DejanLekic Nov 24 '13 at 16:35
  • @DejanLekic Strings can be resized. Making them immutable beats the purpose. (+ it caused some errors for me before: http://stackoverflow.com/questions/20168136/linker-error-cannot-link-d16typeinfo-hayayaa6-initz ) – Jeroen Nov 24 '13 at 16:39
  • No offense, but it seems like you do not understand the reasoning behind making strings immutable... Even Java has String as immutable type now! :) I see you are a JavaScript programmer - do you know that even JavaScript strings are now immutable!?!? Every operation on an ECMAScript string results in a NEW string. – DejanLekic Nov 24 '13 at 17:17
  • @DejanLekic I know why they are immutable, I know how they are immutable, and I know `immutable string[string]` would work in most cases. I don't need to use char[], it just makes more sense to me. Why use a type that was invented to be resizeable, if you don't want them to be resizeable? There is no good reason to use string here. – Jeroen Nov 24 '13 at 17:21
  • @JeroenBollen, char[] are just as resizable. In reality, immutable string[string] and immutable char[][char[]] is the same type in D. – he_the_great Nov 24 '13 at 18:47
  • Sorry got part of that wrong, the key in the second is actually a const(char)[] and not an immutable(char)[]. – he_the_great Nov 24 '13 at 18:54

2 Answers2

3

Well you can define the values of an immutable associative array within a constructor.

Ex.

static immutable int[string] myArray;

static this()
{
    myArray["hi"] = 100;
}

You may want to use a mutable buffer first and assigning that to the immutable buffer.

Bauss
  • 2,767
  • 24
  • 28
3

You should use ":" instead of "=".

immutable (char[][char[]]) = ["testk": "testv", "testk2": "testv2"];
Jeroen
  • 15,257
  • 12
  • 59
  • 102