Hey Yutaro,
I’m glad my explanation has helped make more sense of what’s happening. These coding structures can be difficult to fully understand at first, especially if you like to get to the bottom of things
The mapping only defines the data type of the keys, which in our example is uint
(unsigned integer).
mapping(
uint => User
) users;
We have just choosen to use the same uint value, input into the function as a parameter with the name id
, as both …
(i) the value assigned to the 1st struct property which also has the name id
; and
(ii) the uint
key which each User instance we create is mapped to when assigned to the mapping.
The id
within the struct is a property name, and the id
passed to the function is a parameter name. There is nothing to stop us from using the same name for both. The scope each is defined in is different, and so there is no “clash”.
You are right, though, that we shouldn’t use the same name for a variable and a parameter. If we did, this would generate a compiler warning.
Also, picking up on the other questions you’ve asked about this function in the Additional Solidity Concepts discussion topic …
users[id]
represents the “placement” of our new User instance in the mapping users
. We create a new entry in a mapping by assigning it to a new key in that mapping. The keys in the users
mapping are defined as having to be unsigned integers, and (as I’ve already mentioned above) for these keys, we are choosing to use the unsigned integers input into our function as the id
parameter. The values mapped to each key are defined as having a custom data type User
based on our User struct
. The User
struct has been defined with two properties, and that is the reason why each new value we assign to a new key in the mapping needs to be created with two property values: one for the id
property, and the other for the balance
property. For these two property values, we use the two values input into our function as the id
and balance
parameters.
The id
in users[id]
references the unsigned integer input into our function as the id
parameter. It is placed within square brackets and appended to the mapping name users
, because (as mentioned above) this is the syntax used to assign a new value to a mapping — achieved by mapping it to a key, which is the value placed within the square brackets. The same syntax is also used to reference an entry which is already stored in the mapping.
I hope this helps to answer some more of your questions. Just let me know if anything is still unclear, or if you have any more questions