Struct in Solidity

Struct in Solidity

Structs are basically a data type that the user can create themselves. Solidity provides us with some predefined datatypes like boolean, integers, strings, etc. However, we can create our own in datatype in the format of a structure called a Struct in Solidity. Languages like Java, Javascript also have Structs and Solidity's Struct is similar to those in Java and Javascript. A Struct contains various different datatypes of a group of elements kept together in the Struct. To create a new Struct in Solidity just use the keyword 'struct'. Let's take a look at the syntax to see how we can write our own Struct.

struct struct_name { 
 <datatype> variable_name_1; <datatype> variable_name_2; <datatype> variable_name_3; };

As you can see above Solidity is a statically typed language and hence it requires us to specify the data type of any variable before assigning it a value.

You can write your own Struct like this:

struct Songs {
string songName;
string songArtist
uint songNumber
};

To access the values inside a Struct we use the dot(.) operator. This operator is used between the Struct variable name and the variable inside the Struct we want to access. From the above Struct if we had to access songArtist we would use something like this:

Songs.songName

The following example shows us how to actually use a Struct in Solidity

pragma solidity ^0.8.4;
contract structInSolidity { 
struct Songs {
string songName;
string songArtist
uint songNumber
};

 Songs song;
 function setSong() public { 
song = Songs('Lose Yourself', 'Eminem', 2); 
} 
function getSongId() public view returns (uint) {
 return Songs.songNumber; 
}
}

// output: uint256: 1

If you have any questions, you can find me on my Twitter and LinkedIn