Structs in Solidity

Struct is user-defined/custom data type where you can define some arbitrary object with some properties.

You can't return the struct directly, but can return a tuple of its properties.

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;

contract HelloWorld {

    // struct is user-defined/custom data type where you can define some arbitrary object with some properties
    struct Person {
        uint age; //uint as age cannot be negative
        string name;
    }
    
    Person[] people; // array of Person type
    
    function addPerson(uint _age, string memory _name) public {
        Person memory newPerson = Person(_age, _name);
        people.push(newPerson);
    }
    
    function getPerson(uint index) public view returns (uint age, string memory name) {
        Person memory personToReturn = people[index];
        return (personToReturn.age, personToReturn.name);
    }
    
    function getPersons() public view returns(Person[] memory) {
        return people;
    }
}
Show Comments