Structs

Published by Mario Oettler on

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: