I have the following struct defined as a state variable and conditionally set at runtime.

Transaction private tx;
struct Transaction {
    address to;
    uint value;
    bytes data;

I would like to check if the variable was set before executing a specific portion of my code.

if(tx == ??????){
    //do something

What's the best way to check if the struct is set?

Edit: It is important to note that here the struct is not stored in a mapping. Similar questions on this stackexchange are asking for structs in mapping, here this is not the case.

1 Answer 1


Question is possibly a duplicate of this: What is the zero, empty or null value of a struct?

There are a few ways.

You can check a value if you're sure it implicitly indicates a set/not set condition.

if(tx.to > 0) {} // the address is set

You can be explicit if you prefer:

struct Transaction {
    address to;
    uint value;
    bytes data;
    bool isValid; // set to true whenever the struct holds data

Then you can:

if(tx.isValid) {
  // do something

You'll want to use the explicit method in the case that 0 or empty has meaning your application; meaning you can't use 0 as an indication of valid/inValid.

Not sure it applies in this case, but elimination of doubt about this sort thing is a bonus feature if you buy into the idea of maintaining an index of valid keys to a mapped structure.

Hope it helps.

Update: Some general examples here: Blog: Simple Storage Patterns in Solidity

  • I linked the answer to the other "abstract" question to this Q&A which is more concrete and has its benefits.
    – eth
    Commented Jan 24, 2017 at 9:48
  • The other question you are referencing in your answer is asking for null value of a struct in a mapping in my case the struct is not placed in a mapping. Does your solution works for struct as state variable and not stored in a mapping?
    – Oli
    Commented Jan 24, 2017 at 20:02
  • Sure. The answer above isn't concerned with where the struct came from. The case where people are unsure if a struct is explicitly written to, or just a zeroed out default is often related to retrieving them from mapping, but not necessarily so. Commented Jan 25, 2017 at 0:07

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.