Search⌘ K
AI Features

Copying and Assignment

Explore the concepts of copying and assignment in D structs. Understand how value types are copied directly and how reference types require careful handling to avoid unintended shared data. This lesson helps you manage struct members properly and avoid common pitfalls in value copying.

We'll cover the following...

Structs are value types; this means that every struct object has its own value. Objects get their own values when constructed, and their values change when they are assigned new values.

D
import std.stdio;
struct TimeOfDay {
int hour;
int minute;
}
void main() {
auto yourLunchTime = TimeOfDay(12, 0);
auto myLunchTime = yourLunchTime;
// Only my lunch time becomes 12:05:
myLunchTime.minute += 5;
write("myLunchTime: ");
writefln("%s,%s", myLunchTime.hour, myLunchTime.minute);
// ... your lunch time is still the same:
write("yourLunchTime: ");
writefln("%s,%s", yourLunchTime.hour, yourLunchTime.minute);
}

During a copy, all of the members of the source object are automatically copied to the corresponding members of the destination object. Similarly, assignment involves assigning each member of the source to the corresponding member of the destination.

Struct members that are of ...

svg viewer