What is the difference between enum and shared immutable?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Oct 29 17:16:37 UTC 2020


On Thu, Oct 29, 2020 at 04:56:46PM +0000, IGotD- via Digitalmars-d-learn wrote:
> On Thursday, 29 October 2020 at 16:45:51 UTC, Ali Çehreli wrote:
> > 
> > import std;
> > 
> > immutable string p;
> > 
> > shared static this() {
> >   p = environment["PATH"];  // <-- Run time
> > }
> > 
> 
> Just to clarify, immutable is allowed to be initialized in ctors but
> not anything later than that? Moving p = environment["PATH"] to main
> would generate an error.

1) Module-level immutable can be initialized either as part of the
declaration:

	immutable int x = 1;

2) Or from inside a shared static this():

	immutable int x;
	shared static this() {
		x = 2;
	}

Note that initialization from ctor must be done from `shared static
this()`, which is global; initialization from `static this` is currently
accepted but deprecated, because that's a TLS ctor, and immutables are
implicitly shared so you could potentially break immutability by having
the TLS ctor set it to a different value per thread.  Eventually this
will become a hard error.

The following are errors:

3)
	immutable int x = 1;
	shared static this() {
		x = 2; // NG: cannot modify immutable
	}

4)
	immutable int x;
	void main() {
		x = 3; // NG: cannot modify immutable
	}


T

-- 
Lottery: tax on the stupid. -- Slashdotter


More information about the Digitalmars-d-learn mailing list