I initially solved this by changing ‘memory’ to ‘storage’ since memory would not persist outside the function scope.
After reading through different solutions I realized I didn’t really understand the alternate method changing users[id].balance = balance so I reviewed my code until I better understood how mapping and struct were related (User, the struct vs users, the variable referenced to access data within the struct mapping).
I updated my code from my initial solution to the one below as I believe it’s much more elegant.
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;
}
}