Structs in solidity

Structs in solidity

Structs are custom-defined types that can group several variables. Struct types are used to represent a record. It comprises a name and associated properties which are put in it. It can have similar or different data types all placed in one definition. Suppose you want to keep track of your workers/employees. You might want to track the following attributes about each employee −

  • Name

  • Position

  • Salary/wage

**NOTE: ** The maximum number of variables In a struct is 16. But you can define one struct in another in order to increase the variables

Defining Structs

When defining a Struct, you must use the struct keyword. The struct keyword defines a new data type, with more than one member. The format can be found below:

struct structName { 
   type name1;
   type name2;
   type name3;
}

Example

struct Employee { 
   string name;
   string position;
   uint salary;
}

To access an element of a structure, the dot(.) operation is used between the structure variable name and the structure member that we wish to access. You would use the struct to define variables of structure type.

Example

The example below shows how structs work I solidity

pragma solidity ^0.5.0;

contract structExample {

// Declaring a structure
   struct Employee { 
      string name;
      string position;
      string city
      uint salary;
   }

// Declaring a structure objects
   Employee employee1;
    Employee employee2;

// Defining a function to set values for the fields for structure employee1 and employee2.
    function setEmployeeDetails () public {
       employee1 = Employee("Claire", 
            "Technical writer", 
             200000000);

        employee2 = Employee("Jane Doe", 
            "Web developer", 
            ''Silicon Valley'',
             900000000);
     }

   // Defining function to print employee1 details
     function employee1Details() public view returns (string memory, string memory, uint) {
        return (employee1.name, employee1.position, employee1.salary);
     }

 // Defining function to print employee12 details
      function employee2Details() public view returns (string memory, string memory, uint) {
        return (employee2.name, employee2.position, employee2.city, employee2.salary);
     }

}