Data Structures in Solidity

Arrays, Structure, and Mapping

Beginner Level

Solidity provides several ways to organize and manage data: arrays, structs, and mappings. Understanding these data structures is essential for building efficient and organized smart contracts.

1. Arrays

An array is a collection of elements of the same data type. Solidity supports fixed-size, dynamic, and memory arrays.

a) Fixed-size Arrays

  • Size is defined at compile time and cannot change.
  • Useful when the number of elements is known in advance.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract FixedArrayExample {
    uint256[3] public numbers; // Fixed-size array

    function setNumbers() public {
        numbers[0] = 10;
        numbers[1] = 20;
        numbers[2] = 30;
    }

    function getNumber(uint256 index) public view returns (uint256) {
        return numbers[index];
    }
}

b) Dynamic Arrays

  • Size can grow or shrink during execution.
  • Useful when the number of elements is unknown or variable.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract DynamicArrayExample {
    uint256[] public numbers; // Dynamic array

    function addNumber(uint256 num) public {
        numbers.push(num); // Add element
    }

    function removeLastNumber() public {
        numbers.pop(); // Remove last element
    }

    function getNumber(uint256 index) public view returns (uint256) {
        return numbers[index];
    }
}

c) Memory Arrays

  • Temporary arrays only exist during function execution.
  • Cheaper than storage arrays for computations.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract MemoryArrayExample {
    function sumArray(uint256[] memory arr) public pure returns (uint256) {
        uint256 sum = 0;
        for (uint256 i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return sum;
    }
}

2. Structs

A struct is a custom data type that groups related variables of different types into a single entity. Structs are useful for representing complex data like users, tokens, or products.


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract StructExample {
    struct Person {
        string name;
        uint256 age;
        address wallet;
    }

    Person public person1;

    function setPerson(string memory _name, uint256 _age) public {
        person1 = Person(_name, _age, msg.sender);
    }
}

3. Mappings (Key-Value Pairs)

A mapping is a hash table that maps keys to values. Keys and values can be any type except mappings or dynamic arrays as keys. Mappings are sparse; non-existent keys return default values.


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract MappingExample {
    mapping(address => uint256) public balances;

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function getBalance(address user) public view returns (uint256) {
        return balances[user];
    }
}

4. Nested Mappings & Arrays

a) Nested Mappings


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract NestedMappingExample {
    mapping(address => mapping(string => uint256)) public tokenBalances;

    function depositToken(string memory token, uint256 amount) public {
        tokenBalances[msg.sender][token] += amount;
    }

    function getTokenBalance(address user, string memory token) public view returns (uint256) {
        return tokenBalances[user][token];
    }
}

b) Arrays of Structs


// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract NestedArrayStructExample {
    struct Product {
        string name;
        uint256 price;
    }

    Product[] public products;

    function addProduct(string memory name, uint256 price) public {
        products.push(Product(name, price));
    }

    function getProduct(uint256 index) public view returns (string memory, uint256) {
        Product memory prod = products[index];
        return (prod.name, prod.price);
    }
}

Summary Table

Data Type Description Use Case
Fixed-size Array Array with predefined length Small collections with known size
Dynamic Array Array with flexible length Unknown or growing data
Memory Array Temporary array during function execution Computation without storing on-chain
Struct Custom data type grouping related variables Representing entities like users/products
Mapping Key-value storage Balances, permissions
Nested Mapping Mapping inside a mapping Multi-token wallets, hierarchical data
Array of Structs Dynamic list of custom structs Lists of entities with multiple fields

Continue Learning

Explore more topics in Solidity or browse other tutorials.