Struct in Solidity

whiteboard crypto logo
Published by:
Whiteboard Crypto
on

Structs are reference-type variables that are constructed of multiple other variables and treated as objects. They can be very useful when storing a large amount of data that is all grouped in a similar way. Here is an example of how you can create a new struct, including what you can do with it:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
 
contract structExample{

    struct house{
        uint doors;
        uint walls;
        uint peopleLivingInside;
        string houseAddress;
    }

    house public myHouse = house(2, 4, 2, "123 Main Street");

    function changeDoors(uint _newDoors) public {
        myHouse.doors = _newDoors;
    }

    function getHouseData() public view returns(house memory){
        return myHouse;
    }
 
}

In the first section, we are defining what a house is by declaring that a house consists of 4 pieces of data: doors, walls, peopleLivingInside, and the houseAddress. Right now, we aren’t actually creating a new instance of this struct, we are just defining what it consists of.

Next, we create a new struct of the type “house”, which is public and named “myHouse”. We initialize this new house variable by stating specifically that is is a “hosue” and then fill it with the relevant information that the struct requires. In this case, we say it has 2 doors, 4 walls, 2 peopleLivingInside, and that the address is “123 Main Street”.

After that, we create a new function named “changeDoors” which accepts a uint. It stores that uint in a variable that is used later. We then change the value of “doors” in our new struct “myHouse” by simply using an equal sign and then stating what we want to change it to – which is “_newDoors” in this case.

Finally, we have created a function named “getHouseData” that returns a “house”, and in this specific function you can see the house that we are returning is “myHouse”.

You can always import structs defined in other contracts to reduce the total file size of a contract.

whiteboard crypto logo

WhiteboardCrypto is the #1 online resource for crypto education that explains topics of the cryptocurrency world using analogies, stories, and examples so that anyone can easily understand them. Growing to over 870,000 Youtube subscribers, the content has been shared around the world, played in public conferences and universities, and even in Congress.