1

I have a struct containing another struct. The member struct does not yet exist when instantiating the containing struct. Is there a default for a struct (for address, int, etc' I would initialize with default values (0))? I would like to avoid setting every basic type in the member struct to a default value to save gas, if possible.

struct MemberItem {
    uint value1;
    ...
    uint value10;
}

struct Item {
    MemberItem memberItem;
    uint itemId;
}

item = Item({memberItem:0}, itemId:0);

or, do I have to do the folowing?

item = Item({memberItem:MemberItem({value1:0,...,value10:0}, itemId:0);
  • All values default to 0. So if you made a function to get the inner MemberItem from Item it would return a tuple of 0's, one for each uint in the MemberItem – willjgriff Nov 29 '18 at 20:27
1

or, do I have to do the folowing?

item = Item({memberItem:MemberItem({value1:0,...,value10:0}, itemId:0);

yes, with the design you should always initialize all fields

you can also redesign your contract. you need divide those structs and link those by mapping

struct MemberItem {
    uint value1;
    ...
    uint value10;
}

struct Item {
    uint itemId;
}

mapping(uint => MemberItem) itemToMember;

in the mapping uint is itemId (unique item id)

0

In my experience when you face problems like that it means that your design can be better than this. Try to avoid to map your thinking about data in the design of storage, list the data without clustering them and try to find something simpler. Sometimes this does not work, but very often it helps a lot.

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.