mapping - 映射如何在 Solidity 中工作,以及映射与其他流行语言中的另一个概念类似

标签 mapping blockchain ethereum solidity

谁能解释一下映射是如何工作的以及为什么要使用它?就像数组是项目的集合一样。我没有任何关于 Solidity 的经验,我才刚刚开始。我在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;
}
}

最佳答案

基本上,映射相当于其他编程语言中的字典或映射。它是键值存储。

在标准数组中,它是索引查找,例如如果数组中有 10 个元素,则索引为 0 - 9,它看起来像一个整数数组:

[0] 555
[1] 123
...
[8] 22
[9] 5

或者在代码中:

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];
}

所以基本上,您是用对象而不是整数来引用值。键也不必按顺序排列。

关于mapping - 映射如何在 Solidity 中工作,以及映射与其他流行语言中的另一个概念类似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46466792/

相关文章:

java - 对象映射列表作为Class的成员变量

apache - hyperledger sawtooth是apache还是intel公司旗下的?

python - 使用 requests.get().json() 时的 ValueErrors、ProtocolErrors 和 ChunkedEncodingErrors

asp.net-mvc - 使用 ValueInjecter 在具有不同属性名称的对象之间进行映射

c# - 递归映射 ExpandoObject

r - R中按条件映射的值

javascript - 如何在 Solidity 中构建 HTML 解决方案

javascript - 在 Chrome 中关闭登录弹出窗口时,Metamask 不返回 "code 4001 User rejected the request.",但在 Edge 中有效

arrays - Solidity:UnimplementedFeatureError:此处未实现嵌套动态数组

blockchain - 向 Solidity 结构添加一个新字段使以太坊合约停止工作