Unleashing the Power of Structs: A Guide to Organizing Data in Solidity
Shlok Kumar
Posted on February 1, 2023
Solidity Structs: The building blocks for organizing and managing complex data in Ethereum smart contracts.
Record representation is accomplished through the usage of structs in Solidity.
Consider the following scenario: you want to keep track of your books in a library. You may want to keep track of the following characteristics of each book:
Title
Author
Subject
Book ID
Defining a Struct:
The struct keyword must be used in order to define a Struct. The term struct is used to define a new data type that has more than one member. The following is the format of the struct statement:
struct struct_name {
type1 type_name_1;
type2 type_name_2;
type3 type_name_3;
}
Example:
struct Book {
string title;
string author;
uint book_id;
}
Accessing a Struct and its variable:
To access any member of a structure, we use the member access (.) operator, which lets us get to any part (.). It looks like a period between the structure variable name and the structure member that we want to get to. You would use the struct to set up variables of the structure type with the help of this tool. Structures can be used in programs like this one to make things easier for people to understand.
The following code will help you understand how structs work in Solidity:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
contract Todos {
struct Todo {
string text;
bool completed;
}
// An array of 'Todo' structs
Todo[] public todos;
function create(string memory text) public {
// 3 ways to initialize a struct
// - calling it like a function
todos.push(Todo(text, false));
// key value mapping
todos.push(Todo({text: text, completed: false}));
// initialize an empty struct and then update it
Todo memory todo;
todo.text = text;
// todo.completed initialized to false
todos.push(todo);
}
// Solidity automatically created a getter for 'todos' so
// you don't actually need this function.
function get(uint index) public returns (string memory text, bool completed) {
Todo storage todo = todos[index];
return (todo.text, todo.completed);
}
// update text
function update(uint index, string memory text) public {
Todo storage todo = todos[_index];
todo.text = text;
}
// update completed
function toggleCompleted(uint index) public {
Todo storage todo = todos[_index];
todo.completed = !todo.completed;
}
}
For more content, follow me on - https://linktr.ee/shlokkumar2303
Posted on February 1, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.