Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a specific value exists in the mapping table or not?

I have a mapping table whcich stores multiple hashes into that table. What I want to do is that I want the user to add another hash with setinstructors() function and then try to look whether the same hash already exists in the mapping table or not. If the same hash already exists in the table then it should return true esle false. Here's my code:

pragma solidity ^0.4.18;

contract Hash{
bytes32 comphash;

struct hashstruct{
bytes32 fhash;

}
mapping (uint => hashstruct) hashstructs;
uint[] public hashAccts;



function setinstructor(uint _uint,string _fhash) public {
      var a = hashstructs[_uint];
   a.fhash = sha256(_fhash);  
     hashAccts.push(_uint) -1;


}



function getInstructor(uint ins) view public returns (bytes32) {
    return (hashstructs[ins].fhash);
}

   function count() view public returns (uint) {
    return hashAccts.length;
}



function setinstructors(string _comphash) public {
    comphash = sha256(_comphash);

}

function getInstructors() public constant returns (bytes32) {
    return (comphash);
}



}
like image 462
Vishva Patel Avatar asked Dec 10 '22 07:12

Vishva Patel


1 Answers

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.

like image 57
user94559 Avatar answered Dec 27 '22 05:12

user94559