0

The pop() functions works correctly for normal arrays and mappings.

Based on: How to delete an element at a certain index in an array?

When I try to pop() an array of a mapping not work.

Any alternative to remove the gaps?

pragma solidity ^0.8.0;

// SPDX-License-Identifier:  
  
contract test {
 
    mapping (address => uint[]) MyMap;

    constructor(){
        MyMap[msg.sender].push(0);
        MyMap[msg.sender].push(1);
        MyMap[msg.sender].push(2);
        MyMap[msg.sender].push(3);
    }

    //Set last into [2] //1
    MyMap[msg.sender][2] = MyMap[msg.sender][MyMap[msg.sender].length - 1];
    //Delete last array position
    MyMap[msg.sender].pop(); //This line is the problem...

}

2 Answers 2

1

It always helps to show the full code and error. I'm not entirely sure what OwnerIndexes is, because it's not defined in the example. This line MyMap[msg.sender][2] = MyMap[msg.sender][MyMap.length - 1]; should however also be invalid, since MyMap is a mapping and does not have a .length attribute. You probably are looking for MyMap[msg.sender].length.

3
  • OwnerIndexes is MyMap (I forgot change it) I am going to try with your suggestion. Thanks!
    – JTCon
    May 13 at 16:58
  • You are right with the .lenght of array. That fixed that line. Now the problem is when calling the .pop() function--> MyMap[msg.sender].pop(); Any idea? Thanks
    – JTCon
    May 14 at 2:08
  • well.. is this exactly the code that you are executing? The constructor part is only added at the end of a contract's deploy code. meaning the pop() would be called before the push. You cannot pop() an array if it is empty. Although then the line before would also be incorrect. Can you show the full code and error message?
    – phaze
    May 14 at 11:51
0

Answer by leonardoalt in Solidity github:

"Popping an array of mappings is not allowed because you don't know which keys are dirty or not, so the deleting of the mapping does not actually happen. If you have an array of mappings, write to it, delete the array, and read the mapping again, the information is still there. Please see https://docs.soliditylang.org/en/v0.8.13/security-considerations.html#clearing-mappings."

Source: https://github.com/ethereum/solidity/issues/13021#issuecomment-1126682792

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.