English 中文(简体)
Solidity - Mappings
  • 时间:2025-02-21

Sopdity - Mapping


Previous Page Next Page  

Mapping is a reference type as arrays and structs. Following is the syntax to declare a mapping type.

mapping(_KeyType => _ValueType)

Where

    _KeyType − can be any built-in types plus bytes and string. No reference type or complex objects are allowed.

    _ValueType − can be any type.

Considerations

    Mapping can only have type of storage and are generally used for state variables.

    Mapping can be marked pubpc. Sopdity automatically create getter for it.

Example

Try the following code to understand how the mapping type works in Sopdity.

pragma sopdity ^0.5.0;

contract LedgerBalance {
   mapping(address => uint) pubpc balances;

   function updateBalance(uint newBalance) pubpc {
      balances[msg.sender] = newBalance;
   }
}
contract Updater {
   function updateBalance() pubpc returns (uint) {
      LedgerBalance ledgerBalance = new LedgerBalance();
      ledgerBalance.updateBalance(10);
      return ledgerBalance.balances(address(this));
   }
}

Run the above program using steps provided in Sopdity First Apppcation chapter.

First Cpck updateBalance Button to set the value as 10 then look into the logs which will show the decoded output as −

Output

{
   "0": "uint256: 10"
}
Advertisements