pragma solidity 0.7.5;
contract MemoryAndStorage {
mapping(uint => User) users;
struct User{
uint id;
uint balance;
}
function addUser(uint id, uint balance) public {
users[id] = User(id, balance);
}
function updateBalance(uint id, uint balance) public {
users[id].balance = balance;
}
function getBalance(uint id) view public returns (uint) {
return users[id].balance;
}
}
all i did was effectively remove line 17 and in the resulting line 17 added “s{id}” to “user”; then i tested the get function before the update function, and i’m pretty sure it’s working like i want.
could also just add “users[id].balance = user.balance;” to what would originally be line 19 (using my formatting scheme above), but i that involves a basically unused (or only very briefly used, i.e. somewhat redundant) User variable, “user”.
this works?!
“User storage user = users[id];”
how?? the only explanation i could dream up is that users[id].balance is updated when you update user.balance on the next line (from the video, not from my version above, which removes those lines), but that’s completely counterintuitive (coming from javascript where the right side of the equation is simply assigned, not bound… forever… ???)
@jon_m or @thecil, have you any pointers on how i should think about this? i’m wondering how is users[id.balance updated to return the right answer when called from the getBalance function in this first case from the video? it would make more sense to me if getBlance returned the freshly updated “user.balance” but it returns “users[id].balance”, which didn’t think had been updated …?