Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D programming language char arrays

Tags:

arrays

d

dmd

This may sound really stupid. but I've got a strange problem with the D programming language. When I try to create a new array like this:

import std.stdio;

void main()
{
    char[] variable = "value";
    writefln(variable);
}

The DMD compiler always gives me this error:

test.d(5): Error: cannot implicitly convert expression ("value") of type invariant(char[5u]) to char[]

Any idea why? I'm using the 2.014 alpha (available here) for Ubuntu.

like image 628
user32756 Avatar asked Feb 17 '09 14:02

user32756


2 Answers

I was searching around the arrays section of the guide, this may help:

A string is an array of characters. String literals are just an easy way to write character arrays. String literals are immutable (read only).

char[] str1 = "abc";                // error, "abc" is not mutable
char[] str2 = "abc".dup;            // ok, make mutable copy
invariant(char)[] str3 = "abc";     // ok
invariant(char)[] str4 = str1;      // error, str4 is not mutable
invariant(char)[] str5 = str1.idup; // ok, make invariant copy

From here.

like image 60
ryeguy Avatar answered Oct 07 '22 04:10

ryeguy


Basically, what it comes down to is that string literals are stored in a read-only part of memory. char[] is "a mutable array of mutable characters", which would, if written to, generate a run-time crash.

So the compiler is really trying to protect you here.

invariant(char)[] means "a mutable array of invariant characters", which is exactly what it is.

PS: When you don't need it to be a char[], you might want to use auto, as in, auto variable = "value". Frees you from thinking about its type :)

like image 40
FeepingCreature Avatar answered Oct 07 '22 04:10

FeepingCreature