0

I want to delete a struct from an array. The order doesn't matter to me so I want to do something like following where you take the last element in the array to replace the element I want to delete so that there are no gaps in the array.

mapping (address => File[]) myFiles;

function deleteFile(uint _index) public {
    require(_index >= 0, "The index cannot be a negative number");
    
    File[] memory files = myFiles[msg.sender];
    require(_index < files.length, "The index is out of bound");
        
    if (files.length == 1) {
        files.pop();
    } else {
        File memory file = files[files.length - 1];
        files[_index] = files;
        files.pop();
    }
}

However, pop is not available for struct arrays. I also cannot use files.length -- since length is read-only. How do I achieve this?

3
  • You are using a memory array, if you used a storage reference instead it should work: File[] storage files = myFiles[msg.sender]. Another problem you will have with memory arrays is that changes are on memory and will be discarded if they are not explicitly saved to storage.
    – Ismael
    Mar 30, 2021 at 3:46
  • @Ismael most of the answers on the link you provided use array.length -- which doesn't seem to work anymore. Is there no way to delete an element from an array without iterating through the entire array if I wanted to leave no gap?
    – Kevvv
    Mar 30, 2021 at 13:54
  • To delete the last item from use array.pop(), it works for array in storage.
    – Ismael
    Mar 30, 2021 at 15:12

0

Browse other questions tagged or ask your own question.