Definition of Structs

Learn about structs, how they are defined and accessed in D.

Chapter overview

Fundamental types are not suitable to represent higher-level concepts. For example, although a value of type int is suitable to represent the hour of the day, two int variables would be more suitable together to represent a point in time: one for the hour and the other for the minute.

Structs are the features that allow defining new types by combining already existing types. The new type is defined by the struct keyword. By this definition, structs are user-defined types. Most of the content of this chapter is directly applicable to classes as well, especially the concept of combining existing types to define a new type.

This chapter covers only the basic features of structs. You will see more of structs in the following lessons:

To understand how useful structs are, let’s define a function addDuration():

void addDuration(int startHour, int startMinute,
                 int durationHour, int durationMinute,
                 out int resultHour, out int resultMinute) { 
    resultHour = startHour + durationHour;
    resultMinute = startMinute + 
    durationMinute; resultHour += resultMinute / 60;

    resultMinute %= 60;
    resultHour %= 24; 
}

Note: We will ignore the in, out, and unittest blocks in this chapter to keep the code samples short.

Although the function above clearly takes six parameters, it is conceptually taking only three bits of information for the starting time, the duration, and the result (when the three pairs of parameters are considered).

Structs definition

The struct keyword defines a new type by combining variables that are related in some way:

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy