Are there null like thing in solidity

前端 未结 5 1913
旧巷少年郎
旧巷少年郎 2021-02-05 05:33
    struct buyer{
       uint amount;
       Status status;
    }

    mapping(address=>buyer) public buyers;
    mapping(uint=>address) buyerIndex;
    uint publi         


        
相关标签:
5条回答
  • 2021-02-05 06:07

    In solidity every variable is set to 0 by default.

    You should think of mappings as all possible combinations are set to 0 by default.

    In your specific case I would use the following:

    if (buyers[msg.sender].amount == 0)
    
    0 讨论(0)
  • 2021-02-05 06:07

    For integers:

    You could create none variable to use it as a NULL:

    uint256 constant NULL = 0;
    

    Example code for check:

    function isNULL(uint256 variable) internal returns (bool) {
        return variable == NULL;
    }
    

    For bytes32:

    You can follow different approach for bytes:

    bytes32 constant NULL = "";
    

    Example code piece:

    pragma solidity ^0.6.0;
    
    mapping(address => bytes32) public Countries;   
    
    function isCountriesInitialized(address _user) external view returns (bool) 
    {
        if (Countries[_user] == NULL) // Returns true if `Countries[_user]` is not initialized
            return false;
    
        return true;
    }
    

    I observe that on solidity >= v0.6.0 it may return 32 for length even though it is not mapped.

    Example of its returned value:

    b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

    0 讨论(0)
  • 2021-02-05 06:11

    As Viktor said, default value for all possible values in mapping is zero. So if a buyer has not already inserted in mapping, the amount value for that address will be zero. But this approach has a flaw, if a buyer does exists but its balance became zero after some operations, you will treat it as it does not exist.

    I think the best approach is to add a exists member to the buyer struct with bool type. Default value for this member is false and when the buyer get created, you initialize it with true value. So you can check exactly if a buyer exist or not via this member.

    Buyer struct:

    struct buyer{
       uint amount;
       Status status;
       bool exists;
    }
    

    Initialize buyer:

    buyer memory b = buyer(0, status, true);
    

    Check if buyer exists:

    if(buyers[msg.sender].exists) {
      //so can buy
    }
    
    0 讨论(0)
  • 2021-02-05 06:12

    Instead of using one of the values or creating an extra boolean, you can check for the byte size of the structure.

    if (bytes(buyers[msg.sender]).length > 0) {
        // buyer exists.
    }
    
    0 讨论(0)
  • 2021-02-05 06:23

    There is nothing like null in solidity.

    Just check for the length of the address:

    if(buyers[msg.sender].length == 0){
        // do your thing
    }
    

    See also this answer on ethereum stack exchange.

    0 讨论(0)
提交回复
热议问题