Solidity的地址 数组如何判断是否包含一个给定的地址?

Q:

given address[] wallets. What is the correct method to check that the list contains a given address?

Does solidity provide any native list contains function?

If not, is the only way to do a full iteration of the array and check each element?

Are there more memory efficient ways of doing this, maybe a mapping?

A:

Solidity doesn't provide a contains method, you'd have to manually iterate and check.

Using an array for what you're trying to achieve would be a highly inefficient pattern. The best and most cost efficient method is use a mapping data structure. Set the key to be the address and the value to be a boolean. Lists that are too long have the possibility of running out of gas when you're trying to iterate over them.

If you need to iterate through all the keys in the mapping, then you'd need to have an external database to get all the keys. The database can be populated and updated based on events from the smart contract (i.e. an event when the address is added or removed).

最高效的方式不是 循环遍历数组(可能耗光所有的gas),而是 使用mapping,去做。

Example:

contract myWallets
{
mapping (address => bool) public Wallets; function setWallet(address _wallet) public{
Wallets[_wallet]=true;
} function contains(address _wallet) returns (bool){
return Wallets[_wallet];
}
}
上一篇:tomcat启动dubbo报IO异常


下一篇:根据矩阵变化实现基于 HTML5 的 WebGL 3D 自动布局