Thread overview
Member field of type nested struct must be initialized in constructor: Why?
October 22

Consider this almost minimal example:

import std.algorithm;
import std.range;
import std.stdio;

struct S(Nested){
	Nested member; // = I.init; // Uncommenting this wouldn't help
	int g;
	this(Nested member){
		this.member = member;
	}
	
	this(int g){
		this.g = g;
		version(fix)
			member = Nested.init;
	}
	
}

// IFTI to handle type of map
auto makeS(Nested)(Nested member) => S!(Nested)(member);

import std.sumtype;
// This just works and needs no fix
auto makeSum(I)(I i) => SumType!(string, I)(i);

void main(){
	auto input = iota(5).map!(b => b + 1).map!(b => b - 1);

	auto s = makeS(input);
	auto s2 = makeSum(input);
	writeln(s);
	writeln(s2);
}

Running the code with rdmd -version=fix app.d works, but running rdmd -version=fix app.d produces:
Error: field member must be initialized in constructor, because it is nested struct
Why?
I didn't find anything about this in the spec.

October 22

On Sunday, 22 October 2023 at 21:02:32 UTC, Inkrementator wrote:

>

Running the code with rdmd -version=fix app.d works, but running rdmd -version=fix app.d produces:
Error: field member must be initialized in constructor, because it is nested struct

Sorry, obviously it should be:
Running the code with rdmd -version=fix app.d works, but running just rdmd app.d produces:
Error: field member must be initialized in constructor, because it is nested struct

October 22

On Sunday, 22 October 2023 at 21:02:32 UTC, Inkrementator wrote:

>

Running the code with rdmd -version=fix app.d works, but running rdmd -version=fix app.d produces:
Error: field member must be initialized in constructor, because it is nested struct
Why?
I didn't find anything about this in the spec.

Nested structs contain a context pointer that needs to be initialized at runtime. If you don't initialize them, the pointer gets set to null, and the struct will not be able to access its context.

Using .init doesn't fix this because .init is determined at compile time, and also has null in place of the context pointer.

October 23

On Sunday, 22 October 2023 at 23:49:40 UTC, Paul Backus wrote:

>

Nested structs contain a context pointer that needs to be initialized at runtime. If you don't initialize them, the pointer gets set to null, and the struct will not be able to access its context.

I see, thanks for the explanation.

>

Using .init doesn't fix this because .init is determined at compile time, and also has null in place of the context pointer.

In my case, it makes sense to not initialize the object, so this isn't an issue. Void-initialization would probably be better to document my intent, but the compiler won't let me do that.