Are there null like thing in solidity

淺唱寂寞╮ 提交于 2019-12-03 05:00:21

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)

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

uint80 constant NULL = uint80(0);

Waqar Lim

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.

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
}

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