Are there null like thing in solidity

Hao WU picture Hao WU · Jun 16, 2016 · Viewed 20.1k times · Source
    struct buyer{
       uint amount;
       Status status;
    }

    mapping(address=>buyer) public buyers;
    mapping(uint=>address) buyerIndex;
    uint public buyerNum;
    //Order a product.
    function(){
      uint doubleValue=value*2;
      uint amount=msg.value/doubleValue; 
      if(buyers[msg.sender]==null){ //Error in this line
      buyer abuyer=buyer({amount:amount,status:Status.Created}); //Error in this line
      buyerNum++;
      buyerIndex[buyerNum]=msg.sender;
      buyers[msg.sender]=abuyer;
    }else{
      buyers[msg.sender].amount+=amount;
    }
      Order(msg.sender,amount*doubleValue,amount);

 }

If a buyer is not recorded in the buyer mapping, then buyerNum++; but I don't know how to tell whether a buyer is in the mapping

Answer

alper picture alper · Oct 21, 2016

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'