# Solidity Minimalist Tutorial: 7. Mapping
Recently, I have been relearning Solidity, consolidating the finer details, and also writing a "Solidity Minimalist Tutorial" for newbies to learn. Lectures are updated 1~3 times weekly.
Everyone is welcomed to follow my Twitter: @0xAA_Science (opens new window)
WTF Academy Discord: Link (opens new window)
All codebase and tutorial notes are open source and available on GitHub (At 1024 repo stars, course certification is unlocked. At 2048 repo stars, community NFT is unlocked.): github.com/AmazingAng/WTFSolidity (opens new window)
In this section, we will introduce the hash table in Solidity: mapping type.
# Mapping
With mapping type, people can query the corresponding Value by using a Key. For example, a person's wallet address can be queried by their id.
The format of declaring the mapping is mapping(_KeyType => _ValueType), where _KeyType and _ValueType are the variable types of Key and Value respectively. For example:
mapping(uint => address) public idToAddress; // id maps to address
mapping(address => address) public swapPair; // mapping of token pairs, from address to address
# Rules of mapping
- Rule 1: The
_KeyTypeshould be selected among default types insoliditysuch asuint,address, etc. No custom struct can be used. However,_ValueTypecan be any custom types. The following example will throw an error, because_KeyTypeuses a custom struct:
// define a struct
struct Student{
uint256 id;
uint256 score;
}
mapping(Student => uint) public testVar;
Rule 2: The storage location of the mapping must be
storage: it can serve as the state variable or thestoragevariable inside function. But it can't be used in arguments or return results ofpublicfunction.Rule 3: If the mapping is declared as
publicthen Solidity will automatically create agetterfunction for you to query for theValueby theKey.Rule 4:The syntax of adding a key-value pair to a mapping is
_Var[_Key] = _Value, where '_Var' is the name of the mapping variable, and '_Key' and '_Value' correspond to the new key-value pair. For example:
function writeMap (uint _Key, address _Value) public {
idToAddress[_Key] = _Value;
}
# Principle of mapping
Principle 1: The mapping does not store any
keyinformation or length information.Principle 2: Mapping use
keccak256(key)as offset to access value.Principle 3: Since Ethereum defines all unused space as 0, all
keythat are not assigned aValuewill have an initial Value of 0.
# Verify on Remix (use Mapping.sol as example)
Deploy
Mapping.sol
Check initial value of map
idToAddress.
Write new key-value pair

# Summary
In this section,we introduced the mapping type in Solidity. So far, we've learned all kinds of common variables, and then we'll learn control flow such as if-else and while in the coming tutorials.