initializing immutable structs

Simen kjaeraas simen.kjaras at
Sat Mar 27 07:02:49 PDT 2010

On Fri, 26 Mar 2010 06:35:29 +0100, Paul D. Anderson
<paul.d.removethis.anderson at> wrote:

> I want to initialize an immutable struct but I'm encountering two  
> difficulties and I can't find the answer in the documentation. (Wouldn't  
> it be nice if someone wrote a book?)

You mean like this?

> The primary difficulty is that I can't use a static initializer but need  
> to use a constructor instead. But the constructor isn't allowed as it's  
> non-constant expression. How do I declare the struct variable and  
> initialize it separately?

If your constructor is not CTFE-able, you're basically out of luck. The
following kinda works, but will probably not survive optimizations, and is
a horrible hack to break the type system:

struct S {
	int n;
	this( int n ) {
		this.n = n;

immutable S s = S( 4 );

void main( ) {
	void* v = cast( void* )&s;
	( *cast( S* )v ) = S( 4 );

> The second difficulty is that when I declare it immutable I get a "can't  
> implicitly convert an expression of type X to to immutable X" error. I  
> tried an explicit cast and that didn't work.

This is indeed correct. D has a three-part const system, with both mutable
and immutable implicitly castable to const, but nothing castable to
immutable or mutable.

Immutable basically means 'will never change'. Hence, assigning something
that can change (mutable) or something that might change (const) to an
immutable variable will not work.

If you have created a mutable or const struct and want to convert it to
immutable, make sure there are no references to it, and use
std.contract's AssumeUnique

Conversion of POD structs (no pointer or class members) to immutable
should be painless, as they are pure value types and can be safely copied.

> I'm reasonably certain that this is a common idiom. I'm just trying to  
> declare some constants to use later. What am I missing?
> Thanks,
> Paul
> 1st Difficulty -- I can't


More information about the Digitalmars-d-learn mailing list