Structs in Solidity
Table of contents
Solidity struct
What is struct?
In Solidity, a struct is a user-defined data structure that allows you to define a collection of related variables of different types. It is similar to a struct or object in other programming languages. Here's a simple explanation of structs in Solidity.
How do we declare a struct?
To use a struct, you need to declare it by specifying the variables and their types that make up the structure. For example, you can declare a struct named Person
with variables name
of type string
and age
of type uint
as follows: struct Person { string name; uint age; }
.
How do we initialize a struct?
After declaring a struct, you can create instances of that struct by assigning values to its variables. For example, Person person1 = Person("Alice", 25);
creates an instance of the Person
struct with the name "Alice" and age 25.
Accessing the variables of struct
You can access the variables of a struct instance using dot notation. For example, string personName =
person1.name
;
assigns the value of the name
variable from the person1
instance to the variable personName
.
How to modify variables in a struct
You can modify the variables of a struct instance by assigning new values to them. For example, person1.age = 30;
updates the value of the age
variable in the person1
instance to 30.
Why do we use structs?
Structs are useful for grouping related data together and creating more complex data structures. You can use structs to define custom types and organize your data in a meaningful way. They are commonly used in Solidity to represent entities, records, or objects within smart contracts. Structs provide a way to define custom data structures in Solidity, allowing you to create and manipulate instances of those structures with ease.
Example of a Solidity smart contract that demonstrates different ways of initializing a struct:
In this example, we have a smart contract called StructInitializationExample
that demonstrates the three ways of initializing a struct named Person
.
Initializing a struct using direct assignment: The line
Person memory person1 = Person("Alice", 25);
initializesperson1
directly with the values "Alice" and 25. This method assigns the values to the struct's fields in a single line.Initializing a struct using named arguments: The line
Person memory person2 = Person({name: "Bob", age: 30});
initializesperson2
using named arguments. It explicitly specifies the field names and assigns values to them. This method allows you to assign values in any order.Initializing a struct using individual assignments: The lines
Person memory person3;
person3.name
= "Charlie"; person3.age = 35;
demonstrate individual assignments. Here, we first declare an emptyperson3
struct and then assign values to its fields individually. This method gives you flexibility in assigning values separately.
By deploying and interacting with this contract, you can see how each method initializes the Person
struct using different approaches. Choose the method that suits your needs and coding style.
Pushing a struct into an array
Here's a Solidity smart contract that demonstrates how to push a struct into an array, create a struct and push it immediately into the array, update the array, modify the array, and reset the struct using delete:
In this example, we have a smart contract called StructArrayExample
that showcases different operations on an array of structs (Person
). Here are the features demonstrated by the contract:
Pushing a struct into the array: The
addPerson
function takes a name and age as parameters, creates a newPerson
struct, and pushes it into thepeople
array usingpeople.push(newPerson)
.Creating a struct and pushing it immediately into the array: The
addPersonImmediately
function demonstrates creating aPerson
struct inline and immediately pushing it into thepeople
array usingpeople.push(Person(_name, _age))
.Updating the array by modifying an existing struct: The
updatePerson
function allows updating the name and age of a specific struct in thepeople
array by providing the index. It usesrequire
to ensure a valid index is provided and then modifies the struct in-place usingperson.name
= _name
andperson.age = _age
.Modifying the array directly by index: The
modifyPerson
function allows modifying the name of a specific struct in thepeople
array by providing the index. It usesrequire
to ensure a valid index is provided and directly assigns the new name usingpeople[_index].name = _newName
.Deleting a struct in the array to reset it: The
deletePerson
function allows deleting a specific struct from thepeople
array by providing the index. It usesrequire
to ensure a valid index is provided. It replaces the struct at the given index with the last struct in the array usingpeople[_index] = people[people.length - 1]
, and then removes the last element of the array usingpeople.pop()
.
By interacting with this contract, you can add, update, modify, and delete structs within the `people.
You can create instances of structs and use them within your Solidity contracts to represent and manipulate data more efficiently and conveniently.
Check out my other articles on Solidity Basics (Solidity Data Types and Operators)**, [solidity inheritance](favourajaye.hashnode.dev/solidity-inheritance), Solidity fallback function and function overloading, Variables and control structures in solidity, Solidity Functions, Libraries in solidity, Abstract contracts and Interfaces in solidity, [Guidelines on becoming a Blockchain Developer in 2023 (Solidity)](medium.com/coinsbench/guidelines-on-becomin..), [What is blockchain?](medium.com/web3-magazine/what-is-blockchain..), [All you need to know about web 3.0](medium.com/web3-magazine/all-you-need-to-kn..), [Solidity: Floating points and precision](medium.com/@favoriteblockchain/solidity-flo..), and others
Click here to see the Github repo for this 100 days of solidity challenge.
Don’t forget to follow me, put your thoughts in the comment section, and turn on your notifications.
Subscribe to my newsletter
Read articles from Favour Ajaye directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Favour Ajaye
Favour Ajaye
smart contract developer