Mappings

Learn how to use mappings to develop smart contracts in Solidity.

We’ve already learned about arrays, the first built-in data structure provided by Solidity. While they're very handy, in many cases, we need to track multiple key-value pairs and quickly get a value for a particular key. While this could be implemented using arrays, it would be slow and expensive to execute.

To efficiently support this host of use cases, Solidity has another data structure called mapping. We'll learn how we can use mappings in Solidity and apply them to implement a new smart contract.

Name service

To make this lesson more practical, we start with implementing a new smart contract. This smart contract will allow registering human-readable names for Ethereum addresses, which can otherwise be long and cumbersome to use and share.

We'll call our contract NameService, and this smart contract will have two main features, as follows:

  • Allows recording a human-readable name associated with an Ethereum address

  • Allows getting an address by its name

This is similar to the ENS application that we saw in the first chapter. Just like with ENS, we'd be able to register a human-readable name and then share this name with someone else instead of sharing the long Ethereum address. If they need an Ethereum address, e.g., to send Ether to it, they could later use this smart contract to read the address value associated with the shared name.

Technically, we could implement this contract using an array where we'd store address names. The problem with this is that if we have a lot of registered names, finding a name in an array might be expensive and require a lot of gas. Fortunately, there's a better way.

Mappings in Solidity

For cases like these, Solidity provides another data structure that allows us to store a value for a particular key and get a value associated with a key. In a mapping, a key and value can be of any type. Mappings are similar to hash table implementations in other programming languages, like dict in Python, HashMap in Java, etc.

To define a mapping in Solidity, we need to use the mapping keyword and then provide types for keys and values in the map:

Get hands-on with 1200+ tech skills courses.