Understanding Mappings in Solidity

Mappings in solidity is another data Structure that MUST be understood if you are to able to write solidity fluently. Mapping in Solidity allows you to store a Key-Value pair. This means you can have a unique key and a corresponding value as the data. Mappings also help you implement data-like behavior in your smart contract. Mappings can be created where the keys are the Id's and then the Values are the data. Let's see how we create a mapping in Solidity.

Mapping.PNG

First, we declare the mapping with the mapping keyword. Then we next specify the data types for the key and the value. We specified the data type for the Key to be uint and the data type for the value to be a string. This mapping will contain the database of names, where the keys are the id's and then the values are the names.

In other to add some names to the database we would use a constructor function to be able to do that.

Mapping 2.PNG In the constructor above, we simply passed the key within the [] brackets, and then we assign the new string value to the key.

Let's see how to use mappings in more complex data structures. First, we will create a Car Struct that will store some specific data about that car.

Mapping 3.PNG The Struct in solidity allows us to create custom data in solidity. Here the struct allows us to track and store the car's name, number, and owner's name. Now let us create the Mapping where we can store the cars based on their unique id's. Mapping 4.PNG

Here we have specified that the key is a unit and the value is the car. Now let us create a function to add a new car. Mapping 5.PNG

In this function it accepts the following parameters: The Car's id, name, carNumber, and ownersName. A new struct is built inside of this function from these parameters and then it is added to the car mappings with a new id. The complete code looks like this. You can test and run to see the behavior of this contract in the Remix IDE. Mapping 6.PNG

Finally, we also have nested mapping. Mapping inside another Mapping. This is used for creating more complex data types. For example, we can use the nested mappings to create an address that stores the brand of the individual cars gotten. This brand address is assigned to an individual Etherueum address.

Mapping 7.PNG

This carbrand mapping is a nested mapping that uses the address as the key while the value is the car mappings above: the name, carNumber, ownersName, Now to be able to add a new carbrand to this mapping.

Mapping 8.PNG

we assign the new carbrand mappings using the sender's address as the key. The final code looks like this, you can then try and run this code on Remix.

mapping 9.PNG

This is Day 7 of my 100daysofcode challenge where I am learning solidity and sharing my journey into becoming a blockchain developer. You can follow me on Twitter to follow my Journey.