Asking a const-related fix [Was: Re: DMD workforce contribution]
Jonathan M Davis
jmdavisProg at gmx.com
Mon Nov 7 02:57:09 PST 2011
On Monday, November 07, 2011 05:49:52 bearophile wrote:
> Given how much often I find this problem in D coding, is someone willing and
> able to write a patch to allow code like this (it's in Bugzilla, with
> normal priority)?
>
>
> const struct Foo {
> const int[5] a;
> const int[] b;
> const int[int] aa;
> this(in int n) pure {
> this.a[] = n; // line 6
> this.b = new int[5];
> this.b[0] = n; // line 8
> this.aa[1] = 2; // line 9
> }
> }
> void main() {}
>
>
> The latest DMD gives:
>
> test.d(6): Error: slice this.a[] is not mutable
> test.d(8): Error: this.b[0] isn't mutable
> test.d(9): Error: this.aa[1] isn't mutable
I don't think that any of those are _supposed_ to work. When dealing with a
const or immutable variable, it can only be initialized, not assigned to. For
this.a[] = n;
you're assigning all of the elements of n to all of the corresponding elements
in a. That's an assignment, so of course it doesn't work. If you want to copy
the array, then use
this.a = n.dup;
or
this.a = n.idup;
For
this.b[0]
you're assigning an element in the array. It's const, so that's not legal. The
same goes with
this.aa[1] = 2;
That would be altering aa, which isn't legal. const variables can be
initialized but _can't_ be assigned to. If you want to do something fancier
than a simple initialization, you're going to need to create another array
which you do everything to and _then_ initialize the const array with that.
The errors that you're running into are completely by design.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list