Struct Literals and Static Members
You’ll get to learn about struct literals and static members in this lesson.
We'll cover the following...
Struct literals
Similar to being able to use integer literal values like 10
in expressions without needing to define a variable, struct
objects can be used as literals as well.
Struct
literals are constructed by the object construction syntax.
TimeOfDay(8, 30) // ← struct literal value
Let’s first rewrite the main()
function using what we have learned. The variables will be constructed by the construction syntax and be immutable
this time:
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() {immutable periodStart = TimeOfDay(8, 30);immutable periodDuration = TimeOfDay(1, 15);immutable periodEnd = addDuration(periodStart, periodDuration);writefln("Period end: %s:%s", periodEnd.hour, periodEnd.minute);}
Note that periodStart
and periodDuration
need not be defined as named variables in the code above. Those are in fact temporary variables in this simple program, which are used only for calculating the periodEnd
variable. They could be passed to addDuration()
as literal values instead:
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() {immutable periodEnd = addDuration(TimeOfDay(8, 30), TimeOfDay(1, 15));writefln("Period end: %s:%s", periodEnd.hour, periodEnd.minute);}
Static members
Although objects mostly need individual copies of the struct
's ...