Data Location Assignment

#21
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];//memory is a temporary storage, to get a persistent one, switch to storage. like here. I could update the balance with this.
         user.balance = balance;
    }

    function getBalance(uint id) view public returns (uint) {
        return users[id].balance;
    }
0 Likes

#22

Thanks Capa

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 memory user = users[id];
User storage user = users[id];
user.balance = balance;
// uint balance = balance; doesn’t work
}

function getBalance(uint id) view public returns (uint) {
    return users[id].balance;
}

}

0 Likes

#23
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 memory user = users[id]; - Removed 
         //user.balance = balance; - Removed 
         users[id].balance = balance;
    }

    function getBalance(uint id) view public returns (uint) {
        return users[id].balance;
    }

}
0 Likes

#24

Update the balance of the user stored in the users mapping which is part of storage. That way it will persist between function calls:

function updateBalance(uint id, uint balance) public {
     users[id].balance = balance;
}
0 Likes