Data Location Assignment


#1

the topic didn’t exist yet, so I created it

pragma solidity 0.5.1;
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;
    }

}

#2

@Capaburro thanks for making this thread

@filip I would suggest updating the forum link on the course slide to this thread

My answer

Change the storage type of ‘user’ within the ‘updateBalance’ function from ‘memory’ to ‘storage’. I believe this allows it to modify the variable value on a global level, rather than only locally within the function.


#3

Thank you, I have updated it,.


#4

pragma solidity 0.5.1;
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;
}

}