0
0
Blockchain / Solidityprogramming~5 mins

Structs in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Structs help you group related data together in one place. They make your code easier to understand and manage.

When you want to store information about a person, like name and age.
When you need to keep details about a product, such as price and quantity.
When you want to organize data about a transaction, like sender, receiver, and amount.
Syntax
Blockchain / Solidity
struct StructName {
    Type1 variable1;
    Type2 variable2;
    // more variables
};
Structs group different types of data under one name.
Each variable inside a struct is called a member or field.
Examples
This struct stores a person's name and age.
Blockchain / Solidity
struct Person {
    string name;
    uint age;
};
This struct holds product details like name, price, and quantity.
Blockchain / Solidity
struct Product {
    string productName;
    uint price;
    uint quantity;
};
Sample Program

This simple contract defines a Product struct with a name and price. It sets a product in the constructor and lets you get its details.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract Store {
    struct Product {
        string name;
        uint price;
    }

    Product public product;

    constructor() {
        product = Product("Book", 10);
    }

    function getProduct() public view returns (string memory, uint) {
        return (product.name, product.price);
    }
}
OutputSuccess
Important Notes

Structs help keep related data organized and easy to access.

You can create variables of struct type to store data.

Structs improve code readability and reduce errors.

Summary

Structs group related data into one unit.

Use structs to organize complex data clearly.

Structs make your blockchain code easier to manage.