Hey if a contract only has a few state variables, what is the advantage/disadvantage of storing them in a struct?


A struct is advantageous if a set of variables can describe another variable with multiple instances. For example, if we have a birth certificate registry contract for newborn babies, a struct might look like:

struct Person{
    string name;
    uint birthdate; //write with block.timestamp; written as a block height
    enum gender;
    uint height;
    uint weight;
mapping (uint => Person) people;
uint personID;

In this case, there will be multiple instances of Person - one for every baby whose birth certificate is registered in this contract. Each Person can be described by a set of other variables, such as name, birthdate, gender, height, and weight.

  • One of the main disadvantage when using structs is that the gas fee is considerably higher than just passing the simple type vars around. The main reason for that is the fact that structs cannot simply be created on the stack just like simple types. Instead, they are created either in storage (contract data) or in memory, just like arrays. – nergall Jan 25 '17 at 19:24

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.