Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check that object is null in solidity mapping

I have this solidity mapping

mapping (string => Ticket) public myMapping;

I want to check if myMapping[key] exists or not. How can I check?

like image 869
Anas Hadhri Avatar asked Dec 22 '19 22:12

Anas Hadhri


People also ask

Is there a null in Solidity?

There is nothing like null in solidity.

How do you check if a value is in a mapping Solidity?

First, get the value of an object using syntax mapping[key] and it returns a struct object. It checks a struct object property value greater than zero(0). Another way, is to check the bytes length of an object is zero or not.

What is Calldata in Solidity?

Calldata is an immutable, temporary location where function arguments are stored, and behaves mostly like memory . It is recommended to try to use calldata because it avoids unnecessary copies and ensures that the data is unaltered. Arrays and structs with calldata data location can also be returned from functions.


2 Answers

The entire storage space is virtually initialized to 0 (there is no undefined). So you have to compare the value to the 0 value for your type. For example, mapping[key] == address(0x0) or mapping[key] = bytes4(0x0).

like image 133
Diego B Avatar answered Oct 19 '22 18:10

Diego B


There is no direct method to check whether the mapping has particular key. But you can check if mapping property has value or not. The following example considered that the Ticket is the struct with some property.

pragma solidity >=0.4.21 <0.6.0;

contract Test {

    struct Ticket {
       uint seatNumber;
    }

    mapping (string => Ticket) myMapping;

    function isExists(string memory key) public view returns (bool) {

        if(myMapping[key].seatNumber != 0){
            return true;
        } 
        return false;
    }

    function add(string memory key, uint seatNumber) public returns (bool){            
        myMapping[key].seatNumber = seatNumber;            
        return true;
    }
}
like image 41
Divyang Desai Avatar answered Oct 19 '22 19:10

Divyang Desai