Table of Contents
In Solidity, a struct is a user-defined type that represents a composite data structure, similar to a class in object-oriented programming. A struct can contain multiple fields of different types, and you can use it to define complex data structures that can be used to represent real-world entities.
A Solidity struct is useful for organizing and encapsulating data in a smart contract. A struct can contain multiple fields of different types, allow you to define complex data structures that can be used to represent real-world entities, and they can help you write more readable and maintainable code.
Main purposes that a Solidity struct serves
1. Organizing data
2. Encapsulating data
Structs can be used to create a logical separation between different parts of your data model. For example, you could define a struct to represent a user account, and then use that struct to store all of the data related to a user in one place. This can make it easier to manage your data and avoid conflicts between different parts of your contract.
3. Modeling real-world entities
Structs can be used to represent real-world entities in your contract, such as users, products, or orders. This can make it easier to work with your data and understand the relationships between different entities in your contract.
4. Improving code reuse
Structs can be used as building blocks for more complex data structures, such as arrays and mappings. This can allow you to reuse your struct definitions in multiple places in your contract, which can save you time and improve the maintainability of your code.
Overall, structs are a powerful tool in Solidity that can help you organize and encapsulate your data, model real-world entities, and improve the reuse and maintainability of your code.
How to define a struct in Solidity
with examples 👇🏼
struct Person {
string name;
uint age;
}
In this example, the Person
struct has two fields: name
, which is a string, and age
, which is an unsigned integer. You can create an instance of the Person
struct and set its fields like this:
Person alice;
alice.name = "Alice";
alice.age = 30;
You can also define a struct with an array field, like this:
struct Person {
string name;
uint age;
uint[] favoriteNumbers;
}
In this example, the Person
struct has a field called favoriteNumbers
that is an array of unsigned integers. You can access and modify the elements of the array just like you would with any other array in Solidity.
—