-
During the course and instructions on mapping, I found that there were two ways in which Patrick did this: First Way:
Second Way:
My question is, What is the correct way of mapping a value? Do we need to add the '+=' sign or just the '=' sign should do? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
I will keep this as simple as possible for beginners: The first way - think of the mapping nameToFavoriteNumber as a kind of dictionary; with name as key, which points to the data (here, favouriteNumber) which it contains. And you can access that data by doing nameToFavoriteNumber[key] (which is essentially calling the key which points to our data). Example (visual representation for interpretation, not precise): The second way - We are using To be completely technical, it is essentially a basic hash map BTW, inapt category: Since this is a Q&A question, it is best advised to mark it as such, so people with doubts can reference to the marked answer in the future. Hope this helps and all the best with the course! |
Beta Was this translation helpful? Give feedback.
-
@Mark-Four Both ways are correct and both have their own use case. nameToFavoriteNumber[_name] = _favoriteNumber; This is only assigning a favorite number. addressToAmount[msg.sender] += msg.value; On the other hand, this is assigning the value as well as incrementing. This is equivalent to this: addressToAmount[msg.sender] = addressToAmount[msg.sender] + msg.value; Now you can see both ways are the same. |
Beta Was this translation helpful? Give feedback.
I will keep this as simple as possible for beginners:
The first way - think of the mapping nameToFavoriteNumber as a kind of dictionary; with name as key, which points to the data (here, favouriteNumber) which it contains. And you can access that data by doing nameToFavoriteNumber[key] (which is essentially calling the key which points to our data).
Now to be precise, since we are using the assignment operator
=
here, it assigns_favoriteNumber
(or data) to the key_name
(or our key)Example (visual representation for interpretation, not precise):
nameToFavoriteNumber["Alice"] = 7
nameToFavoriteNumber = {"Alice": 7} // Alice points to 7 (Alice ----> 7) inside our mapping
The second way - …