gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:32:43 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com