Apart from different built-in data types in Solidity programming language such as Integer, String, address, etc., Solidity gives us the flexibility to create our own data type using struct, which is just a collection of variables under a single name. This allows us to organize data according to our needs.
We define a struct with the keyword struct
followed by its name and curly braces. Inside, we add more than one member, as a struct contains members of different data types except for a member of its own data type.
struct Struct_name { type1 type_name_1; type2 type_name_2; . . . type16 type_name16; }
struct User{ address userAddress; uint balance; bool isVerified; }
Here, we defined a struct called User
. The struct has three members, userAddress
of data type address, balance
of data type integer, and isVerified
of a boolean data type.
A struct object is declared using the name of the early defined struct followed by the object name and a semicolon. For our example, the declaration will look like this: User object_name;
. To assign a value to a struct object, we either assign every member a value one by one or we assign it all at once by passing the value of each member as an argument on the struct.
User alice; function addUsers(address userAddress, uint balance, bool isVerified) public{ User memory bob = User(userAddress,balance,isVerified); alice.userAddress = 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4; alice.balance = 0; alice.isVerified = false; }
We created the struct object bob
by assigning its member value all at once through the arguments passed on the struct User
. For the variable alice
, we assigned values on each member one by one.
To access a struct’s members, we add a dot followed by the member name on a struct object. To get Alice’s balance, we just need to call alice.balance
, and to get Alice’s address, we call alice.userAddress
.
function getUserAddress()public view returns(address){ return alice.userAddress; }
In this shot, we learned how to create our own Solidity custom data type.
RELATED TAGS
CONTRIBUTOR
View all Courses