D Structs - D Programming Language

What is D Structs?

D arrays allow you to define the type of variables that can hold several data items of the same type but the structure is another user defined data type available in D programming, which allows you to combine records items of different kinds.

Systems are used to represent a document, suppose you need to maintain track of your books in a library. You might want to track the following attributes about each book:

  • Title
  • Author
  • Subject
  • Book ID

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a new data type, with more than one member for your program. The format of the struct statement is this:

The structure tag is optional and every member definition is a normal variable definition, such as int I; or float f; or any other legitimate variable definition. on the end of the structure's definition, earlier than the final semicolon, you can specify one or more structure variables but it is optional. here is the way you would declare the ebook structure:

Accessing Structure Members

To access any member of a structure, we use the member access operator (.). The member access operator is coded as a period between the structure variable name and the structure member that we wish to access. You would use struct keyword to define variables of structure type. Following is the example to explain usage of structure:

When the above code is compiled and executed, it produces the following result:

Structures as Function Arguments

You can pass a structure as a function argument in very similar way as you pass any other variable or pointer. You would access structure variables in the similar way as you have accessed in the above example:

When the above code is compiled and executed, it produces the following result:

Structs initializations

Structs can be initialized in two forms, one using construtor and other using the {} format. An example is shown below.

When the above code is compiled and executed, it produces the following result:

Static Members

Static variables are initialized only once. For example to have unique ids for the book, we can make the book_id as static and increment the book id. An example is shown below.

When the above code is compiled and executed, it produces the following result:

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

D Programming Language Topics