Mapping
我不明白用於更新儲存在結構類型中的映射的定義,如下所述
struct Payment { uint amount; uint timestamp; } struct Balance { uint totalBalance; uint numPayments; mapping(uint => Payment) payments; } mapping(address => Balance) public balanceReceived; function sendMoney() public payable { balanceReceived[msg.sender].totalBalance += msg.value; Payment memory payment = Payment(msg.value, now); balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPa yments] = payment; balanceReceived[msg.sender].numPayments++; }
在上面的智能合約中,為什麼這是用於添加到 Balance 結構內的支付映射的定義:
balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment;
並不是:
balanceReceived[msg.sender].payments[_index] = payment;
餘額結構中與獲取密鑰的 numPayments 的連接在哪裡
正如您所期望的那樣,
numPayments
它本質上是一個索引。需要注意的關鍵是它是每個地址的索引。該
balanceReceived
映射將地址映射到平衡結構,其中最初numPayments
將設置為零。對於與該合約互動的每個地址都是如此。每次他們付款時,這numPayments
只會增加該特定地址的餘額。您當然可以為所有使用者餘額保留一個全域
_index
,並每次都增加它。這樣可以正常工作,唯一的區別是該索引將針對所有地址的所有付款增加。在這種情況下,您將失去有關該特定地址進行了多少付款的資訊。