Are there null like thing in solidity

家住魔仙堡 提交于 2020-01-12 04:23:12

问题


    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


回答1:


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)



回答2:


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

uint80 constant NULL = uint80(0);




回答3:


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.




回答4:


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
}



回答5:


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

if( bytes( buyers[msg.sender] ).length > 0 ) {
    // buyer exists
}


来源:https://stackoverflow.com/questions/37852682/are-there-null-like-thing-in-solidity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!