pragma solidity 0.5.1;
// cursus Smartcontracts
// 10 sept 2020
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 memory user = users[id]; // original line code
// First solution is to update from volatile memory to permanent storage
User storage user = users[id];
user.balance = balance;
// better Second solution is to select directly the record of the mapping with [id] and Update the balance
// users[id].balance = balance ;
}
function getBalance(uint id) view public returns (uint) {
return users[id].balance;
}
}
I suggest 2 solutions, first is to change memory to storage but this will consume permanent storage
2e solution is to use the mapping directly
See code for implementation