Efficient way to create/copy immutable struct instance with modified data

Merlin Diavova md at mdiavov.com
Fri Nov 19 17:38:53 UTC 2021


Hi all,

I'm trying to figure out the most efficient way to create 
modified instances of immutable structs.

Currently, I'm doing the following:

```d
immutable struct Node {
	string label;
	Node parentNode;
	NetworkPort port;

	auto withLabel(string newLabel)
	{
		return Node(newLabel, this.parentNode, this.port);
	}

	auto withParentNode(Node newParentNode)
	{
		return Node(this.label, newParentNode, this.port);
	}

	auto withNetworkPort(NetworkPort newPort)
	{
		return Node(this.label, this.parentNode, newPort);
	}
}
```
Coming from a scripting language the above makes the most sense.
In D, this an efficient way to do it? Are there any best 
practices around this?

Thanks in advance

Merlin


More information about the Digitalmars-d-learn mailing list