There's no such thing as "existence" in a Solidity mapping.
Every key maps to something. If no value has been set yet, then the value is 0.
For your use case, hashstructs[n].fhash > 0 is probably sufficient. If you want to be explicit, add a bool exists to your struct and set it to true when you add something. Then use hashstructs[n].exists to check for existence.
There's no such thing as "existence" in a Solidity mapping.
Every key maps to something. If no value has been set yet, then the value is 0.
For your use case, hashstructs[n].fhash > 0 is probably sufficient. If you want to be explicit, add a bool exists to your struct and set it to true when you add something. Then use hashstructs[n].exists to check for existence.
If you want to check whether a key exists in the mapping then you can check the byte length. If the length is zero that means the key doesn't exist else key is present in the mapping. A Sample Example is:-
function checkUser(string memory user_id) public view returns(bool){
if(bytes(PassHash[user_id]).length>0){
return true;
}
else{
return false;
}
}
How can you figure out if a certain key exists in a mapping (in Solidity)?
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).
smartcontracts - Undeclared Identifier Error for _exists() Function in Solidity Contract Using OpenZeppelin - Stack Overflow
blockchain - solidity mapping check if element already exists - Stack Overflow
remix - Check if user exists using mapping in solidity - Ethereum Stack Exchange
In Javascript, we might check for the existence of an object member like this:
if (object[key]) {
// do something
} else {
// do something else
}
I tried if(mapping[key]) { ... } in Solidity but that didn't work...
"Note that there is no type conversion from non-boolean to boolean types as there is in C and JavaScript, so if (1) { ... } is not valid Solidity." (https://github.com/ethereum/wiki/wiki/Solidity-Tutorial#control-structures).
mapping[key] == 0 is not a valid expression, so... how do we check for the existence of a key in a mapping?