In updateBalance function, the variable user is just executed inside the function and it will not save outside it, because of memory statement.
The fastest solution to solve this problem is to change the data location from memory to storage, to save it permanently.
pragma solidity 0.5.12;
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 {
User storage user = users[id];
user.balance = balance;
}
function getBalance(uint id) view public returns (uint) {
return users[id].balance;
}
}
The cheapest solution will be to rewrite the function whit the same body as addUser function. In this way there isn’t any extra data stored permanently (eg. into variable user).
pragma solidity 0.5.12;
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] = User(id, balance);
}
function getBalance(uint id) view public returns (uint) {
return users[id].balance;
}
}