Mutate immutable inside shared static constructor

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Mar 23 21:53:43 UTC 2024


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





More information about the Digitalmars-d-learn mailing list