I have this solidity mapping
mapping (string => Ticket) public myMapping;
I want to check if myMapping[key]
exists or not. How can I check?
There is nothing like null in 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.
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.
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).
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With