zoukankan      html  css  js  c++  java
  • 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];
        }
    }
  • 相关阅读:
    Java 实现常见内排序
    markdown基本语法
    HashMap (JDK1.8) 分析
    jQuery总结
    JS 数组 常用方法
    CSS样式 解决文字过长显示省略号问题
    Python中的 __name__属性的含义和作用
    http协议详细介绍
    Http和Https的区别
    爬虫——requests库使用方法
  • 原文地址:https://www.cnblogs.com/x-poior/p/10268232.html
Copyright © 2011-2022 走看看