Solidity Mapping – What is the Zero Value for a String?

mappingsoliditystringstruct

How to verify that a string, or a struct with only string properties, is initialised or not, inside of a mapping?

According to the docs, it means checking that the element of the mapping is at its 0-value, which is unclear to me when talking about strings.

contract C {
    mapping (address => string) m1;
    mapping (address => StringStruct) m2;

    struct StringStruct {
        string someString; // Always defined when initialising this struct
        // There could be other string properties here...
    }
    
    function amIInBothMappings() returns (bool) {
         // Check that both m1[msg.sender] and m2[msg.sender].someString are non-0
    }
}

In the example: what is the best way to implement amIInBothMappings that checks that msg.sender is un-initialised in both mappings m1 and m2?

Best Answer

One way is to check for the length of a String:

if (bytes(m1[msg.sender]).length != 0 && bytes(m2[msg.sender].someString).length != 0)
    // do your thing

See the answer I posted here

Related Topic