Structs

Published by Mario Oettler on

Last Updated on 12. June 2023 by Mario Oettler

Structs allow us to define new custom types in Solidity. They are basically a collection of variables. Structs are very useful inside arrays and mappings.

Declaration

Structs are declared like that:

Struct StructName {
	type variable_name_1;
	type variable_name_2
}

Since structs are data types, we have to declare a variable to assign a value to their members. The declaration of the variable is made like any other type.

StructName myStruct;

You can see the code example below.

pragma solidity 0.8.20;


contract structTest{
    
    struct User {
        uint256 balance;
        string name;
    }
    
    User public user;
}

In line 6, we define the struct with the name User (notice the uppercase U) and add two members in lines 7 and 8. Then, in line 11, we declare a variable with the name user (notice the lowercase u).

Adding Values to Structs

If you want to assign values to a member (variable) of a struct, you have multiple options:

  1. point-notation,
  2. colon-notation,
  3. short-notation

You can find examples of all three possibilities in the code example:

pragma solidity 0.8.20;


contract structTest{
    
    struct User {
        uint256 balance;
        string name;
    }
    
    User public user;
    
    function addToStruct_point_notation() public{
        user.balance = 100;
        user.name = "Bob";
    }
    
    
    function addToStruct_colon_notation() public{
        user = User({
            balance: 120,
            name: "Alice"
        });
    }
    
    function addToStruct_short_notation() public{
        user = User(150,"Chris");
    }
}
Categories:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: