Hi @cincinnato,
You’ve nearly got it:
Yes - this happens in the addUser function with this code:
users[id] = User(id, balance);
/* A User struct instance is created and assigned to the mapping users.
A mapping is always stored persistently in storage (no need to state
the data location with the keyword storage).
The id parameter is used as the mapping key */
We aren’t sending anything in this contract, but we are replacing the initial balance (saved in the mapping by calling the addUser function) with a new balance i.e. updating it by calling the updateBalance function. You are correct that we can first save this new amount (the new balance) in memory, by assigning it to a local variable, as follows:
//'local variable declared (data type = User struct instances)
User memory user;
// local variable given a balance property, and new balance assigned to it
user.balance = balance;
However, we don’t have to use this inefficient intermediary step. We can just assign the new balance directly to the mapping (to persistent storage): see Step 4 below.
This isn’t happening in this contract. The new balance is passed into the updateBalance function as an argument/parameter.
Yes, that’s correct. We can either assign the new balance already saved in memory (in the user
variable in Step 2) to the users
mapping using the key id
, as follows (3rd line):
User memory user; // Step 2
user.balance = balance; // Step 2
// replaces the existing User instance in the mapping
users[id] = user;
… or we can miss out Step 2 altogether and just directly assign the new balance to the mapping (save it directly to persistent storage) using either of the following 2 alternatives:
// ALTERNATIVE 1
/* sets the balance property of the User instance (with key'id) in the mapping
to the new balance */
users[id].balance = balance;
// ALTERNATIVE 2
// creates a pointer called 'user' (direct reference) to users[id] in the mapping
User storage user = users[id];
/* sets the balance property of the User instance in the mapping, which is
referenced by the pointer, to the new balance */
user.balance = balance;
I hope that helps, and makes things (a bit) clearer