DEV Community

Cover image for Mappings in Solidity
AbhayPatel98
AbhayPatel98

Posted on

Mappings in Solidity

Mappings in Solidity
Have you ever heard of a hash table? If you've taken one or two computer science courses, chances are you have! If not, don't worry, you're in the right place. Let's jump in… 🛩
A hash table is a data structure that implements an associative array (also referred to as a "dictionary"). In an associative array, data is stored as a collection of key-value pairs. The position of the data within the array is determined by applying a hashing algorithm to the key.
As seen above, a key represents some data to be stored in the hash table data structure. That key is fed into a hash function which produces a hash value. That hash value dictates the index where the data, pertaining to the key, will be stored in the hash table. 🧩
Any time you "look up" (hence why hash tables are referred to as "dictionary" data structures!) a value by key, you will get whatever value is stored in the hash table back. Hash functions are deterministic, so you will always get the same value back as long as you provide the same key.
Hash Table Data Structures Are Efficient 🏎
Hash tables enable very efficient searching, in fact, they enable the "holy grail" O(1) search time. Hash tables do not require a brute force search or a for loop to look up a value thanks to the deterministic nature of hash functions! 🐐 You can just say, gimme whatever value is held at this key and the hash table data structure will comply. ⚡️

Mappings
In Solidity, hash tables are called mappings. They function pretty much the exact same as hash tables. 🤷
Mappings act as hash tables which consist of key types and corresponding value type pairs.
They are defined like any other variable type in Solidity:
**
mapping(_KeyType => _ValueType) public mappingName;**
mapping(_KeyType => _ValueType) public mappingName;
**
Useful for address Association
Solidity mappings are particularly useful for address association.
Thanks to mappings, you can associate an Ethereum address to a specific value. Here are a few examples we could use address association for:
Keeping track of how many sodas a user has purchased from a vending machine smart contract:
mapping(address => uint) public sodasPurchased;.

Top comments (2)

Collapse
 
leonardpuettmann profile image
Leonard Püttmann

Neat short article, thanks for posting. :)

Collapse
 
abhaypatel profile image
AbhayPatel98

Thanks, Mate.