20

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?

1

2 Answers 2

30

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
  • 1
    indeed, the bytes().length trick seems to work well!
    – lajarre
    Commented Jun 6, 2016 at 12:55
0

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 and acknowledge you have read our privacy policy.

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