Thread overview
Mutate immutable inside shared static constructor
March 23

I've not used static constructors before, but it seems like the following should not be allowed:

import std.stdio;

immutable int x;

@safe shared static this()
{
    x.writeln(); // 0
    x = 5;
    x.writeln(); // 5
    x = 6;
    x++;
    assert(x == 7);
}

Should I file a bug to require that x is only written to once? That would make it consistent with class constructors:

class C
{
    immutable int x;
    this()
    {
        x = 5;
        x = 6; // error, x initialized multiple times
    }
}
March 23
On Saturday, March 23, 2024 3:23:23 PM MDT Nick Treleaven via Digitalmars-d- learn wrote:
> I've not used static constructors before, but it seems like the following should not be allowed:
>
> ```d
> import std.stdio;
>
> immutable int x;
>
> @safe shared static this()
> {
>      x.writeln(); // 0
>      x = 5;
>      x.writeln(); // 5
>      x = 6;
>      x++;
>      assert(x == 7);
> }
> ```
> Should I file a bug to require that `x` is only written to once?
> That would make it consistent with class constructors:
>
> ```d
> class C
> {
>      immutable int x;
>      this()
>      {
>          x = 5;
>          x = 6; // error, x initialized multiple times
>      }
> }
> ```

Yes, it's a bug. It's a clear violation of the type system if a non-mutable variable is ever given a value more than once. It should be initialized, and then it should be treated as illegal to ever assign to it - or to do anything else which would mutate it. So, clearly, the logic in static constructors with regards to non-mutable variables is overly simple at the moment.

- Jonathan M Davis



March 23
On Saturday, 23 March 2024 at 21:53:43 UTC, Jonathan M Davis wrote:
> Yes, it's a bug. It's a clear violation of the type system if a non-mutable variable is ever given a value more than once. It should be initialized, and then it should be treated as illegal to ever assign to it - or to do anything else which would mutate it. So, clearly, the logic in static constructors with regards to non-mutable variables is overly simple at the moment.

Thanks, filed:
https://issues.dlang.org/show_bug.cgi?id=24449
March 24
On Saturday, 23 March 2024 at 21:59:57 UTC, Nick Treleaven wrote:
> On Saturday, 23 March 2024 at 21:53:43 UTC, Jonathan M Davis wrote:
>> Yes, it's a bug. It's a clear violation of the type system if a non-mutable variable is ever given a value more than once. It should be initialized, and then it should be treated as illegal to ever assign to it - or to do anything else which would mutate it. So, clearly, the logic in static constructors with regards to non-mutable variables is overly simple at the moment.
>
> Thanks, filed:
> https://issues.dlang.org/show_bug.cgi?id=24449

Thanks for your prompt answer.