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

Posted 未将对象引用设置到对象的实例

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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];
    }
}

 

以上是关于Solidity的地址 数组如何判断是否包含一个给定的地址?的主要内容,如果未能解决你的问题,请参考以下文章

Solidity智能合约如何判断地址为0或空

怎么判断一个字符数组包含于另一个字符数组

如何判断一个数组里是不是包含一个数

JQuery如何判断值中是不是包含某个值?

如何高效地判断数组中是否包含某特定值

Solidity - 内存布局