【问题标题】:How to know if a specific value exists in the mapping table or not?如何知道映射表中是否存在特定值?
【发布时间】:2018-09-13 05:28:55
【问题描述】:

我有一个映射表,其中将多个哈希存储到该表中。我想要做的是我希望用户使用 setinstructors() 函数添加另一个哈希,然后尝试查看映射表中是否已经存在相同的哈希。如果表中已经存在相同的哈希,那么它应该返回 true esle false。这是我的代码:

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);
}



}

【问题讨论】:

    标签: ethereum solidity smartcontracts


    【解决方案1】:

    在 Solidity mapping 中没有“存在”这样的东西。

    每个键都映射到某些东西。如果尚未设置值,则值为 0。

    对于您的用例,hashstructs[n].fhash > 0 可能就足够了。如果您想明确一点,请将bool exists 添加到您的struct 并在添加内容时将其设置为true。然后使用hashstructs[n].exists 来检查是否存在。

    【讨论】:

      【解决方案2】:

      如果要检查映射中是否存在键,则可以检查字节长度。如果长度为零,则表示密钥不存在,否则映射中存在密钥。一个示例是:-

      
          function checkUser(string memory user_id) public view returns(bool){
              if(bytes(PassHash[user_id]).length>0){
                  return true;
              }
              else{
                  return false;
              }
          }
      

      【讨论】:

      • 根据 v0.8.6: if (abi.encodePacked(PassHash[user_id]).length > 0) { delete balances[addr]; }
      猜你喜欢
      • 2016-03-19
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-11
      相关资源
      最近更新 更多