2

Let's say I have a struct.

struct test {
  uint x;
}

test[] all;
mappings(uint => test) map;

function bla(){
   test memory structTest = test(5);
   all.push(structTest);
   map[10] = structTest;
}

After the code, will structTest be saved in one place and then my array and map will save the references to it or it will be stored separately in map and array ?

If the latter, how can I create struct and store it in mapping and array so that I don't waste space ?

1 Answer 1

2

A copy of structTest is saved separately in the array and in the mapping.

In order to get rid of this redundancy, you can maintain an array of keys instead of values:

uint[] all; // instead of `test[] all;`
mappings (uint => test) map;

function bla() {
    test memory structTest = test(5);
    all.push(10); // instead of `all.push(structTest);`
    map[10] = structTest;
}

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.