[Ethereum] How to you figure out if a certain key exists in a mapping, Struct defined inside Library (in Solidity)

mappingsolidity

pragma solidity ^0.4.8;

library Library {
  struct data {
     unit val;
   }
}

contract Array{
    using Library for Library.data;
    mapping(address => Library.data) clusterContract;

    function addCluster(address id) returns(bool){
        if(clusterContract[id] == address(0) ){ //error occurs!
            clusterContract[id] = list;
            return true;
        }
        return false; 
    }
}

Following comparission if(clusterContract[id] == address(0)) gives the following error:

Operator == not compatible with types struct Library.data storage ref and address
E               if(clusterContract[id] == address(0) ){...

[Q] How could I fix this error?

Best Answer

You can't directly find out if any key exists in a mapping, ever, because they all exist.

mapping(key => value) name;

creates a namespace in which all possible keys exist, and values are initialized to 0/false.

If you want to check that a value was explicitly set, and not merely the default (0), then you have to program something. In some cases, value > 0 is enough, but if 0 has meaning in your application, then another struct member can help ... bool isValue;, for example.

library Library {
  struct data {
     uint val;
     bool isValue;
   }
}

contract Array{
    
    using Library for Library.data;
    mapping(address => Library.data) clusterContract;

    function addCluster(address id) returns(bool){
        if(clusterContract[id].isValue) throw; // duplicate key
        // insert this 
        return true; 
    }
}

I noticed "addCluster" has the appearance of a contract factory (in progress), so you probably intend to keep track of contracts created as you go.

I assembled a little summary of different ways of organizing common data patterns in Solidity. It might be helpful to take a look here: Blog: Simple Storage Patterns in Solidity

Hope it helps.

Related Topic