solidity – Mapping Multiple Keys to a Single Struct

mappingsoliditystruct

I've done some research on mappings and structs, and I know it's possible to store structs in a mapping as the value but not the key.

I am trying to creating a mapping of addresses => structs where multiple addresses are pointing to the same struct.

For example, I have the following test structure and mapping.

struct test{
uint nonce;
address friend;
}

mapping (address => test) testMapping;

Is it possible for me have two different addresses mapping to the same struct (not just the same data – I don't want to make a copy for efficiencies sake)?

If I were to writing the following code, would I be making a copy of the data within the struct or simply pointing two different keys to the same location in memory within the mapping?

testMapping[address1].nonce = 1;
testMapping[address1].friend = address2;
testMapping[address3] = testMapping[address1];

AKA, do the above commands copy the values from testMapping[address1] into testMapping[address2], or does it simply point testMapping[address2] to the same memory location as testMapping[address1], in which case, when I update one, both are updated?

Thanks for any help.

Best Answer

Yes, you would be making a copy.

What you could do instead is to just have an array of tests and then map addresses to array indices.

struct test{
    uint nonce;
    address friend;
}

mapping (address => uint) testMapping; //Maps addresses to index in `tests`
test[] tests;