Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

solidity
ethereum
blockchain

What is a struct in Solidity?

David Kathoh

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.

How to define a struct in Solidity

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.

Syntax

struct Struct_name { 
   type1 type_name_1;
   type2 type_name_2;
          .
          .
          .
    type16 type_name16;      
}
Syntax

Example

struct User{ 
   address userAddress;
   uint balance;
   bool isVerified;
}
Example

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.

How to declare a struct object

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;
}
Struct object creation

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.

How to access a struct’s members

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

solidity
ethereum
blockchain
RELATED COURSES

View all Courses

Keep Exploring