User is declared as a state variable therefore it is automatically and permanently stored in the storage. With the memory keyword after User inside the updateBalance function, it created a new User in the memory and no longer referencing to the User declared as a state variable.
This is my solution:
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 {
User storage user = users[id]; // changed memory to storage
user.balance = balance;
}
function getBalance(uint id) view public returns (uint) {
return users[id].balance;
}
}