DEV Community

Cover image for Day 13 - Structs
Vedant Chainani
Vedant Chainani

Posted on • Updated on

Day 13 - Structs

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 13 of 30 in Solidity Series
Today I Learned About Structs in Solidity.

Structs in Solidity allows you to create more complicated data types that have multiple properties. You can define your own type by creating a struct.

They are useful for grouping together related data.

Structs can be declared outside of a contract and imported in another contract. Generally, it is used to represent a record. To define a structure struct keyword is used, which creates a new data type.

Syntax:

struct <structure_name> {  
   <data type> variable_1;  
   <data type> variable_2; 
}
Enter fullscreen mode Exit fullscreen mode

Example:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract structType {
    struct Student {
        string name;
        string gender;
        uint roll_no;
    }

    // Declaring a structure object
    Student student1;

    // Assigning values to the fields for the structure object student2
    Student student2 = Student("Jeff","Male",1);

    // Defining a function to set values for the fields for structure 
    // student1
    function setStudentDetails() public {
        student1 = Student("Teresa","Female",2);
    }

    // Defining a function to get Student Details
    function studentInfo() public view returns (string memory, string memory, uint) {
        return(student1.name , student1.gender , student1.roll_no);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output -
When we run setStudentDetails it stores values in the structure student2
and when we call the studentInfo function we get

{
    "0": "string: Teresa",
    "1": "string: Female",
    "2": "uint256: 2"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)