Preventing .init for Archive struct, Programming in D, page 295

Brother Bill brotherbill at mail.com
Fri Sep 12 15:20:38 UTC 2025


Is is possible to 'disable' .init for a struct?

source/app.d
```
import std.stdio;

void main()
{
	// Can still create Archive with an empty filename. We can't 
have that.
	auto noDefault = Archive.init;
	writefln("fileName: [%s]", noDefault.fileName);
}

// adding a constructor automatically removes default 
constructor, so need to disable it.
struct Archive
{
	string fileName;

	@disable this();						// Cannot call default constructor
	@disable this(ref const(typeof(this)));	// Disable the copy 
constructor
	@disable this(this);					// Disable the postblit.  Always do 
this.
	@disable typeof(this) opAssign(ref const(typeof(this))); // 
Disable assignment operator

	this(string fileName) {	// Explicit constructor, can be called.
		this.fileName = fileName;
	}
}

```

Console output:
```
fileName: []
```


More information about the Digitalmars-d-learn mailing list