Mapping
Mapping is a data structure in Solidity that allows a programmer to store, retrieve and modify data in a key-value pair format. It is similar to a hash table or dictionary in other languages.
Example:
Let's assume we want to store a list of people and their ages. We can do this with a mapping like this:
Initialization & Assignment
On Initialization, all possible key-value pairs are already initialized.
Accessing unassigned key-value pairs will return the default value for that value type.
This is because the hash that points to the location in storage has not been generated & we have not written a value thus far.
Assignment of values must be done inside a function
cannot simply do
myMapping[1] = "test"
(like python)
Example
On initialization,
myMapping[1]
will return the default bool value of false.Then we call
setValue
setting ->myMapping[1]
= trueSubsequently, when we call
myMapping[1]
, we are returned true as set earlier.
Nested Mapping
This creates a mapping from an address to a mapping of uints to strings.
This allows us to store a string value associated with a given address and a given uint.
This could be used to store user data associated with a particular address and a particular event or transaction.
Last updated