Construction
Learn about the construction of structs in this lesson.
Let’s continue our discussion from the previous lesson. Consider the following code:
Press + to interact
import std.stdio;struct TimeOfDay {int hour;int minute;}TimeOfDay addDuration(TimeOfDay start,TimeOfDay duration) {TimeOfDay result;result.minute = start.minute + duration.minute;result.hour = start.hour + duration.hour;result.hour += result.minute / 60;result.minute %= 60;result.hour %= 24;return result;}void main() {TimeOfDay periodStart;periodStart.hour = 8;periodStart.minute = 30;TimeOfDay periodDuration;periodDuration.hour = 1;periodDuration.minute = 15;immutable periodEnd = addDuration(periodStart, periodDuration);writefln("Period end: %s:%s", periodEnd.hour, periodEnd.minute);}
The first three lines of main()
are about constructing the periodStart
object, and the next three lines are about constructing the periodDuration
object. In every three lines of code first, an object is being defined and then its hour
and minute
values are being set.
In order for a variable to be used in a safe way, that variable must first be constructed in a consistent state. Because construction is so common, there is a special construction syntax for struct objects:
Press + to interact
import std.stdio;struct TimeOfDay {int hour;int minute;}TimeOfDay addDuration(TimeOfDay start,TimeOfDay duration) {TimeOfDay result;result.minute = start.minute + duration.minute;result.hour = start.hour + duration.hour;result.hour += result.minute / 60;result.minute %= 60;result.hour %= 24;return result;}void main() {TimeOfDay periodStart = TimeOfDay(8, 30);TimeOfDay periodDuration = TimeOfDay(1, 15);immutable periodEnd = addDuration(periodStart, periodDuration);writefln("Period end: %s:%s", periodEnd.hour, periodEnd.minute);}
The values are automatically assigned to the members in the order that they are specified: Because ...