Hi @sph73,
Your solution works
but you’re right that we can achieve the same result more concisely.
The initial idea of this assignment is to update the existing balance by replacing it with the new one, which is input into the function. This is the logic behind the suggested solutions shown in the video.
However, I do actually think that it makes more sense to approach things the way you have, and to add an amount (input into the function) to the user’s existing balance. But there is no need to use an additional local variable to do this. You can just add the input amount at the same time as assigning it …
User storage user = users[id];
user.balance = user.balance + balance;
We can also make this statement more concise by using an addition assignment operator +=
(instead of the assignment operator =
) …
User storage user = users[id];
user.balance += balance;
Both of these alternatives perform exactly the same operation.
However, if we add to, instead of replacing, the existing balance, I think the code looks clearer and more readable if we also change the name of the balance
parameter to amount
, because we are adding an amount to the existing balance (to give a new total balance), rather than replacing it with a new balance.
function updateBalance(uint id, uint amount) public {
User storage user = users[id];
user.balance += amount;
}
There is always more than one solution to these assignments, and alternative interpretations are equally valid.
This is essentially correct …
By making this change, we are now directly updating the user’s balance stored persistently in the mapping. So, the change to the user’s balance is now a permanent one (at least until it is updated again).
Previously, we were only making a temporary copy of the struct instance (the user’s record stored in the mapping), and updating that with the new balance instead. This temporary copy (together with the new balance) was then lost when the function had finished executing.
Just let us know if anything is still unclear, or if you have any further questions 