typestar

Mappings in Solidity

The key-value store; missing keys read as zero.

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

// A mapping is a key-value store; missing keys read as zero.
contract ShareLedger {
    mapping(address => uint256) public shares;
    mapping(address => mapping(uint256 => bool)) public votedOn;

    function issue(address member, uint256 amount) external {
        shares[member] += amount;
    }

    function castVote(uint256 proposal) external {
        votedOn[msg.sender][proposal] = true;
    }

    function hasShares(address member) external view returns (bool) {
        return shares[member] > 0;
    }
}

How it works

  1. mapping(address => uint256) has no length and no iteration.
  2. Mappings nest: address to proposal to bool.
  3. Reading an absent key returns the type's zero, never reverts.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
519
Tokens
97
Three-star pace
55 tpm

At the three-star pace of 55 tokens a minute, this run takes about 106 seconds.

Type this snippet

Step 1 of 3 in Storage, step 5 of 28 in Language basics.

← Previous Next →