Lesson 07 of 25
Arrays & Mappings
Fixed and dynamic arrays, key-value mappings, and nested data structures.
BeginnerFixed & Dynamic Arrays
Solidity supports both fixed-size and dynamic arrays. Dynamic arrays can grow at runtime; fixed arrays have compile-time sizes.
Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Arrays {
// Fixed-size array — size is part of the type
uint256[5] public fixedArr = [1, 2, 3, 4, 5];
// Dynamic array — grows as needed
uint256[] public dynArr;
function push(uint256 val) public {
dynArr.push(val); // appends element
}
function pop() public {
dynArr.pop(); // removes last element
}
function length() public view returns (uint256) {
return dynArr.length;
}
function getElement(uint256 i) public view returns (uint256) {
require(i < dynArr.length, "Index out of bounds");
return dynArr[i];
}
}
Mappings
Mappings are hash tables — O(1) key-value lookups. Every possible key exists by default, returning the zero value of the value type. Mappings cannot be iterated or have their keys enumerated.
Solidity
contract Mappings {
// address => balance
mapping(address => uint256) public balances;
// address => (spender => allowance) — nested mapping
mapping(address => mapping(address => uint256)) public allowances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function approve(address spender, uint256 amount) public {
allowances[msg.sender][spender] = amount;
}
function getBalance(address user) public view returns (uint256) {
return balances[user]; // returns 0 if user never deposited
}
}
Iterating Over a Mapping
To iterate a mapping, maintain a separate array of keys. This pattern is very common in Solidity.
Solidity
contract IterableMapping {
mapping(address => uint256) public scores;
address[] public players; // track keys manually
function addScore(address player, uint256 score) public {
if (scores[player] == 0) {
players.push(player); // only add new players
}
scores[player] = score;
}
function topScore() public view returns (address best, uint256 highest) {
for (uint i = 0; i < players.length; i++) {
if (scores[players[i]] > highest) {
highest = scores[players[i]];
best = players[i];
}
}
}
}
Memory Arrays
Use
memory arrays for temporary data inside functions. They must have a fixed size when created in memory.
Solidity
contract MemoryArrays {
function doubled(uint256[] memory input)
public pure returns (uint256[] memory result)
{
result = new uint256[](input.length); // allocate
for (uint i = 0; i < input.length; i++) {
result[i] = input[i] * 2;
}
}
}