2017-09-28 55 views
0

任何人都可以解釋mapping的工作原理以及它爲什麼使用它?像數組是一個項目的集合。我沒有紮實的經驗,我剛剛開始。我在solidity官方文檔頁面上找到了這個代碼。繪圖如何在穩固中起作用,並且映射類似於其他流行語言中的另一種概念

pragma solidity ^0.4.11; 

Contract CrowdFunding { 
// Defines a new type with two fields. 
struct Funder { 
    address addr; 
    uint amount; 
} 

struct Campaign { 
    address beneficiary; 
    uint fundingGoal; 
    uint numFunders; 
    uint amount; 
    mapping (uint => Funder) funders; 
} 

uint numCampaigns; 
mapping (uint => Campaign) campaigns; 

function newCampaign(address beneficiary, uint goal) returns (uint campaignID) { 
    campaignID = numCampaigns++; // campaignID is return variable 
    // Creates new struct and saves in storage. We leave out the mapping type. 
    campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0); 
} 

function contribute(uint campaignID) payable { 
    Campaign storage c = campaigns[campaignID]; 
    // Creates a new temporary memory struct, initialised with the given values 
    // and copies it over to storage. 
    // Note that you can also use Funder(msg.sender, msg.value) to initialise. 
    c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value}); 
    c.amount += msg.value; 
} 

function checkGoalReached(uint campaignID) returns (bool reached) { 
    Campaign storage c = campaigns[campaignID]; 
    if (c.amount < c.fundingGoal) 
     return false; 
    uint amount = c.amount; 
    c.amount = 0; 
    c.beneficiary.transfer(amount); 
    return true; 
} 
} 

回答

1

基本上,映射相當於一個字典或其他編程語言的地圖。這是重要的價值存儲。

在標準數組中,它是索引查找,例如如果有數組中的10個元素的索引是0 - 9,它看起來像這樣作爲一個整數數組:

或者代碼:

uint[] _ints; 

function getter(uint _idx) returns(uint) { 
    return _ints[_idx]; 
} 

所有按鍵都按順序基於它們被添加到陣列的順序。

映射工作稍有不同,描述它的最簡單方法是使用重要查找。因此,如果這是地址映射到一個整數,那麼它會是這個樣子:

[0x000000000000000A] 555 
[0x0000000000000004] 123 
.... 
[0x0000000000000006] 22 
[0x0000000000000003] 6 

或者在代碼

mapping(address => uint) _map; 

function getter(address _addr) returns(uint) { 
    return _map[_addr]; 
} 

因此,基本上,你有一個對象,而不是整數參考值短。鑰匙也不必按順序。

+1

很好的解釋。此外,映射解釋在這裏:https://ethereum.stackexchange.com/questions/9893/how-does-mapping-in-solidity-work 我想補充說,有可能有一個映射內部映射在Solidity ;) –

相關問題