What is struct initialization in D programming?
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:
- The construtor format
- 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 constructorClothes 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);}
Explanation
-
Line 3: We define the
Clothesstruct using thestructkeyword. -
Lines 4 and 5: We define our
structdata items. -
Line 11: We initialize an instance of the
Clothesstruct asClothe1, giving the data items values. Here, we use the constructor method for initialization. -
Line 16: We initialize an instance of the
Clothesstruct asClothe2, giving the data items values. Here, we use{}format for initialization.
- Lines 21 and 22: We print our output.