Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d programming
community creator

What is struct initialization in D programming?

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

What is a struct in D programming?

A struct is a data type that allows the combinations of different data items which are user-defined.

How to initialize a struct?

Structs can be initialized in two ways:

  1. The construtor format
  2. The {} format

Example

Let’s look at the example below:

import std.stdio;
struct Clothes {
char [] color;
int size;
};
void main( ) {
//Initializing a struct using a constructor
Clothes Clothe1 = Clothes("Yellow".dup,50 );
printClotheDetails( Clothe1 );
// initializing a struct using the {}
Clothes Clothe2 = {color:"Purple".dup, size:40};
printClotheDetails( Clothe2 );
}
void printClotheDetails( Clothes clothe ) {
writeln( "Clothe color : ", clothe.color);
writeln( "Clothe size : ", clothe.size);
}
Struct initialization

Explanation

  • Line 3: We define the Clothes struct using the struct keyword.

  • Lines 4 and 5: We define our struct data items.

  • Line 11: We initialize an instance of the Clothes struct as Clothe1, giving the data items values. Here, we use the constructor method for initialization.

  • Line 16: We initialize an instance of the Clothes struct as Clothe2, giving the data items values. Here, we use {} format for initialization.

  • Lines 21 and 22: We print our output.

RELATED TAGS

d programming
community creator

CONTRIBUTOR

Chinweuba Elijah Azubuike

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring