16

How to verify that a string, or an enum 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?

22

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

  • 1
    indeed, the bytes().length trick seems to work well! – lajarre Jun 6 '16 at 12:55
1

Another way is to compare the sha3 hashes of the strings

if (sha3(myVariable) != sha3("")) {
 // is not empty string
}

However, this method is probably less efficient.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.