Notes Drawer

Notes Drawer

Solidity's Mapping Data Structure

An interesting data structure that you run into pretty quickly when working with Solidity is mapping.

Mapping in Solidity acts like a hash table or dictionary in any other language.

Data is stored as Key-Value Pairs much like traditional hashes or dictionaries. An interesting feature of the construct is that a key can be any of the built-in data types except for reference types while the value can be of any type.

mappings give the language a powerful capability to handle associations similar to how a database would manager a 1 to 1 or a 1 to n relationship. Mappings can hold other mappings as a value which would give rise to powerful hierarchical structures ( think Folders with Sub folders ) with very fast access to the data at the bottom levels.

The key portion is generally an Ethereum address and the value could be any data that you want associated with that address. What is nice is that the value can be a complex type like a struct.

Essentially you can use the key as a handle to a pretty powerful object as needed.

For example:

struct student{
   string  fullName;
   string  grade;

mapping(address => student) studentRecord;

From here you can now grab individual student information using the student's Address. You can now have millions of students and due to this easy lookup structure you can get the individual you need out quickly.

Share this