0

Very basic question but would appreciate any help understanding this. I don't quite understand the logic behind the += operator within the below mapping. Please see below code

function getBalance() public view returns(uint) {
        return address(this).balance;
    }

    function sendMoney() public payable {
        balanceReceived[msg.sender] += msg.value;
    }

How can you logically add and assign and have - balanceReceived [msg.sender] = balanceReceived [msg.sender] + msg.value?

I am sure I am looking at this the wrong way but the balanceRecieved [msg.sender] is a address so how can you add that to a uint value of msg.value?

1
  • we need to see the mapping definition
    – sola24
    Sep 23, 2022 at 14:37

2 Answers 2

0

without seeing the mapping definition I'd guess it's something like

mapping(address => uint) balanceReceived;

that means balanceReceived[msg.sender] is not an address, it's what an address is mapped to, which is a uint

5
  • Hi Sola. Yes, that makes sense. Thanks for that and yes you were correct - that was the mapping definition. Another question - From what I understand the ` balanceReceived[msg.sender] ` accesses the mapping of the msg.sender address to the uint amount that has been sent but how would it know this uint amount is the amount that has been sent already without that somehow being defined?
    – Wattlebird
    Sep 23, 2022 at 15:01
  • If I understand your question correctly: the value of the uint will only ever change when it is assigned/set some value. It doesn't know anything. msg.value is a global variable in Solidity that "knows" what value that the sender sent with the transaction invoking this payable function
    – sola24
    Sep 23, 2022 at 15:08
  • So my logic would be that essentially in this example balanceReceived[msg.sender] would start with a uint value of 0 and then be incremented by the msg.value which "knows" a certain uint value that the sender had sent?
    – Wattlebird
    Sep 23, 2022 at 15:16
  • yep. that's right
    – sola24
    Sep 23, 2022 at 15:17
  • I understand :) Very much appreciated!
    – Wattlebird
    Sep 23, 2022 at 15:19
0

balanceReceived should be of type mapping(address => uint), and msg.sender is of type address, msg.value is of type uint.

So balanceReceived[msg.sender] is a uint value but not an address.

Does that make sense?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.