What is struct in Solidity: Definition and Usage
struct in Solidity is a custom data type that groups related variables into a single unit, like a container for different pieces of information. It helps organize complex data by bundling multiple values under one name.How It Works
Think of a struct in Solidity as a box that holds different items together. Instead of keeping each item separately, you put them all in one box with labels. This makes it easier to manage and pass around related data.
For example, if you want to store information about a person, like their name, age, and wallet address, you can create a struct called Person that holds all these details. This way, you only need to handle one Person variable instead of many separate variables.
Under the hood, a struct groups variables of different types into one compound type. You can then create variables of this new type and access each part using dot notation, like person.name or person.age.
Example
This example shows how to define a struct called Person and use it to store and retrieve data.
pragma solidity ^0.8.0; contract People { struct Person { string name; uint age; address wallet; } Person public person; function setPerson(string memory _name, uint _age) public { person = Person(_name, _age, msg.sender); } function getPerson() public view returns (string memory, uint, address) { return (person.name, person.age, person.wallet); } }
When to Use
Use struct in Solidity when you want to group related data together to keep your code clean and organized. It is especially useful when dealing with complex data like user profiles, product details, or any entity with multiple attributes.
For example, in a voting contract, you might use a struct to store each voter's information, such as their ID, voting status, and chosen candidate. This makes it easier to manage and update voter data.
Structs also help reduce errors by keeping related data bundled, so you don't accidentally mix up separate variables.
Key Points
- Structs group multiple variables into one custom type.
- They improve code readability and organization.
- You access struct members using dot notation.
- Structs can be stored in memory or contract storage.
- They are useful for modeling real-world entities in smart contracts.